KatInterview

Partition Array by Parity of Frequency

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarrayshash mapstwo pointers

Last updated

Tests in-place partitioning using a hash map to precompute element frequencies, then a two-pointer scheme to rearrange elements without extra array allocation.

Partition Array by Parity of Frequency

You are given a list of integers nums. Your task is to rearrange it in-place so that all elements whose value appears an odd number of times in the original list come before all elements whose value appears an even number of times.

Within each group the relative order of elements must be preserved (i.e. this is a stable partition).

Return the rearranged list (the same list object, modified in-place, is also acceptable).

Tie-breaking / uniqueness: Because the partition is stable, exactly one output is correct for every input.

Details

  • Count frequencies using the original list before any rearrangement.
  • An element belongs to the odd-frequency group if the count of that element in the original list is odd, and to the even-frequency group otherwise.
  • Elements that never appear (count 0) are impossible by definition; every element in the list has count ≥ 1.
  • The function must return the rearranged list.

Constraints

  • 1 ≤ len(nums) ≤ 2000
  • -10^6 ≤ nums[i] ≤ 10^6
  • The list may contain duplicates.
  • An empty list [] should be returned as-is.

Examples

Example 1

Input: partition_by_frequency_parity([3, 1, 2, 1, 3, 2, 2])

Output: [2, 2, 2, 3, 1, 1, 3]

Example 2

Input: partition_by_frequency_parity([5, 5, 7, 7, 7, 1])

Output: [7, 7, 7, 1, 5, 5]

Example 3

Input: partition_by_frequency_parity([4])

Output: [4]

Hints

Hint 1

First, build a frequency map of the original list in one pass before touching element positions.

Hint 2

A stable partition can be achieved without an auxiliary array by collecting the two groups separately, then writing them back — but think about whether you can also do it with two pointers plus a temporary buffer of O(1) extra space per swap step.

Hint 3

After filling in both groups in order, concatenate (odd-frequency group) + (even-frequency group) and copy the values back into the original list, then return it.