Count Occurrences - Problem

Given an array of integers, count how many times each unique element appears in the array.

Return the result as a formatted string where each line contains: element: count

The elements should be displayed in the order they first appear in the original array.

Input & Output

Example 1 — Basic Array with Duplicates
$ Input: nums = [3, 1, 2, 3, 1]
Output: 3: 2 1: 2 2: 1
💡 Note: Element 3 appears 2 times, element 1 appears 2 times, element 2 appears 1 time. Order matches first appearance.
Example 2 — All Unique Elements
$ Input: nums = [5, 4, 3, 2, 1]
Output: 5: 1 4: 1 3: 1 2: 1 1: 1
💡 Note: Each element appears exactly once, so all counts are 1. Output preserves original order.
Example 3 — Single Element Repeated
$ Input: nums = [7, 7, 7]
Output: 7: 3
💡 Note: Only one unique element (7) appears 3 times total.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
INPUT ARRAYFREQUENCY COUNTFORMATTED OUTPUT31231[3, 1, 2, 3, 1]1Count each element2Build frequency map3Preserve orderHash Map:3 → count: 21 → count: 22 → count: 1String Result:3: 21: 22: 1Order preservedfrom inputKey Insight:Hash maps enable O(n) frequency counting while preserving original element orderthrough a second pass - much faster than checking each element separately!TutorialsPoint - Count Occurrences | Hash Map Approach
Asked in
Amazon 25 Microsoft 20 Google 15
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen