1363. Swap Within Families
A school hands out locker numbers, and the locker numbers are listed in the array nums. Two lockers are called cousins when their numbers end in the same decimal digit. The caretaker may swap the numbers at any two positions, at any distance apart, but only when the two numbers are cousins. The caretaker may do this as many times as needed, including zero times.
Return true if the numbers can be made non-decreasing from left to right, otherwise return false. Equal numbers are allowed to sit next to each other. Aim for O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [31,12,21,2]
- Output:
- false
- Explanation:
The numbers 31 and 21 end in 1 and 12 and 2 end in 2; sorting each group in place gives [21, 2, 31, 12], where 21 is followed by 2, so the answer is false.
Example 2
- Input:
- nums = [12,31,21,42]
- Output:
- true
- Explanation:
Swapping the cousins 31 and 21 gives [12, 21, 31, 42], which is ascending, so the answer is true.
Example 3
- Input:
- nums = [5,15,25]
- Output:
- true
- Explanation:
All three numbers are cousins and already ascending, so the answer is true.
Constraints
-
1 ≤ nums.length ≤ 1000 -
0 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log n)
- Space
- O(n)