Rearrange Array by Removing Distinct Values Problem
#4065
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 4065.
You are given an integer array nums.
You start with an empty array ans. Repeat the following operation until nums is empty:
- Identify all distinct values currently present in
nums. - Remove one occurrence of every distinct value currently in
nums, and append those values toansin ascending order.
Return the array ans.
Example 1:
Input: nums = [3,1,3,2,1,3]
Output: [1,2,3,1,3,3]
Explanation:
Operation Appended to ans nums after ans after
1 1, 2, 3 [3, 1, 3] [1, 2, 3]
2 1, 3 [3] [1, 2, 3, 1, 3]
3 3 [] [1, 2, 3, 1, 3, 3]
nums is now empty, so the answer is [1, 2, 3, 1, 3, 3].
Example 2:
Input: nums = [7,7,4,4,4]
Output: [4,7,4,7,4]
Explanation:
Operation Appended to ans nums after ans after
1 4, 7 [7, 4, 4] [4, 7]
2 4, 7 [4] [4, 7, 4, 7]
3 4 [] [4, 7, 4, 7, 4]
nums is now empty, so the answer is [4, 7, 4, 7, 4].
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Counting
Every operation takes one copy of each distinct value that is still left, in ascending order. So count how many times each value occurs in an array cnt.
Then repeat the following until ans has n elements: go through the values in ascending order, and for every value whose count is still positive, append it to ans and decrease its count. Each pass over the values is one operation.
The values are at most 100, so a pass is cheap.
Complexity: O(n * M) time in the worst case, where M is the largest value, and O(M) extra space.
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
mx = max(nums)
cnt = [0] * (mx + 1)
for x in nums:
cnt[x] += 1
ans = []
while len(ans) < len(nums):
for x in range(1, mx + 1):
if cnt[x]:
ans.append(x)
cnt[x] -= 1
return ans