Magicsheet logo

Maximum Number of Pairs in Array

Easy
100%
Updated 6/1/2025

Asked by 1 Company

Maximum Number of Pairs in Array

What is this problem about?

The Maximum Number of Pairs in Array coding problem gives you an array of integers nums. You need to find the maximum number of pairs you can form from the elements of the array. Each pair must consist of two equal elements, and once elements are used in a pair, they cannot be used again.

Why is this asked in interviews?

Altimetrik and similar companies use this as an easy problem to test fundamental data structure usage and counting. It's a straightforward application of hash tables (or frequency arrays for small constraints) to efficiently count occurrences of each number, which then directly leads to forming pairs.

Algorithmic pattern used

Hash Table / Frequency Map: The most efficient way to solve this is to count the frequency of each number in the array. Once you have the counts, for any number x that appears count_x times, you can form floor(count_x / 2) pairs. The total number of pairs is the sum of pairs formed for each unique number. Any remaining odd occurrences of numbers cannot form a pair and are left over.

  1. Initialize a hash map (or dictionary) to store counts of each number.
  2. Iterate through nums: for each number num, increment its count in the map.
  3. Initialize total_pairs = 0 and leftover_elements = 0.
  4. Iterate through the values (counts) in the hash map: a. For each count_x, total_pairs += count_x // 2. b. leftover_elements += count_x % 2. (Optional: some problems ask for leftover elements).
  5. Return total_pairs.

Example explanation

nums = [1, 3, 2, 1, 3, 2, 2]

  1. Frequencies:
    • 1: 2 times
    • 3: 2 times
    • 2: 3 times
  2. Pairs:
    • For 1: 2 // 2 = 1 pair.
    • For 3: 2 // 2 = 1 pair.
    • For 2: 3 // 2 = 1 pair. (1 element of '2' is left over)
  3. Total pairs = 1 + 1 + 1 = 3.
  4. Leftover elements: 1 (from number 2).

Common mistakes candidates make

  • Not using a frequency map: Trying to sort the array and iterate, or using nested loops, can be less efficient or more error-prone. A frequency map simplifies the logic significantly.
  • Incorrectly calculating pairs: Ensure floor(count / 2) logic is used.
  • Ignoring constraints: If nums contains very large numbers but only a small range of distinct numbers, a frequency array might be faster than a hash map. Always consider the value range.

Interview preparation tip

For the Array Hash Table Counting interview pattern, problems involving counting elements or finding frequencies are often best solved with a hash map. This problem is a foundational exercise in using frequency maps to solve problems efficiently.

Similar Questions