Given the array [1,2,3,4,2,5,1], output [2,1]. Write the code to find elements that appear more than once.
1Times asked
Jul 2026Last seen
Jul 2026First seen
💡 Model Answer
Use a hash map (dictionary) to count occurrences of each element. Iterate through the array, incrementing the count for each value. After counting, iterate through the map and collect keys whose count is greater than one. This yields the list of duplicates. Complexity is O(n) time and O(n) space. Example in Python:
python
arr = [1,2,3,4,2,5,1]
counts = {}
for num in arr:
counts[num] = counts.get(num, 0) + 1
result = [num for num, cnt in counts.items() if cnt > 1]
print(result) # [1, 2]This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500