
Problem
Solution
Submissions
Occurrences of Each Element in a List
Certification: Basic Level
Accuracy: 82.35%
Submissions: 34
Points: 5
Write a Python program that counts how many times each element appears in a list and returns a dictionary.
Example 1
- Input: lst = [1, 2, 2, 3, 3, 3]
- Output: {1: 1, 2: 2, 3: 3}
- Explanation:
- Step 1: Create an empty dictionary to store the frequency of each element.
- Step 2: Iterate through the list, counting occurrences of each element.
- Step 3: Element 1 appears once, so add entry {1: 1}.
- Step 4: Element 2 appears twice, so add entry {2: 2}.
- Step 5: Element 3 appears three times, so add entry {3: 3}.
- Step 6: Return the dictionary with all element frequencies.
Example 2
- Input: lst = [4, 4, 4, 4]
- Output: {4: 4}
- Explanation:
- Step 1: Create an empty dictionary to store the frequency of each element.
- Step 2: Iterate through the list, counting occurrences of each element.
- Step 3: Element 4 appears four times, so add entry {4: 4}.
- Step 4: Return the dictionary with the element frequency.
Constraints
- 1 ≤ len(lst) ≤ 10^3
- -10^5 ≤ lst[i] ≤ 10^5
- Time Complexity: O(n) where n is the length of the input list
- Space Complexity: O(n) to store the frequency dictionary
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the
Counter
module fromcollections
to count elements. - Convert the result to a dictionary.