#3011

Find if Array Can Be Sorted

Medium
ArrayBit ManipulationSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Instead of trying to sort the array through swaps, we can categorize the elements based on their set bits and check if we can arrange them in a sorted manner based on these categories.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of tuples where each tuple contains the number of set bits and the original value of the element.
  2. 2Step 2: Sort this list based on the number of set bits first and then by the original values.
  3. 3Step 3: Check if the sorted list maintains the order of the original values.
solution.py9 lines
1# Full working Python code
2
3def count_set_bits(n):
4    return bin(n).count('1')
5
6def can_sort(nums):
7    sorted_nums = sorted(nums)
8    categorized = sorted((count_set_bits(num), num) for num in nums)
9    return all(categorized[i][1] == sorted_nums[i] for i in range(len(nums)))

Complexity note: The sorting step dominates the complexity, making it O(n log n) due to the sort operation on the categorized list.

  • 1Elements can only be swapped if they have the same number of set bits.
  • 2Sorting can be achieved by categorizing elements based on their set bits.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.