|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 3011. Find if Array Can Be Sorted |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/find-if-array-can-be-sorted |
| 6 | + |
| 7 | +=begin |
| 8 | +You are given a 0-indexed array of positive integers nums. |
| 9 | +In one operation, you can swap any two adjacent elements if they have the same number of set bits. You are allowed to do this operation any number of times (including zero). |
| 10 | +Return true if you can sort the array, else return false. |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +Input: nums = [8,4,2,30,15] |
| 14 | +Output: true |
| 15 | +Explanation: Let's look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation "10", "100", and "1000" respectively. The numbers 15 and 30 have four set bits each with binary representation "1111" and "11110". |
| 16 | +We can sort the array using 4 operations: |
| 17 | +- Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15]. |
| 18 | +- Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15]. |
| 19 | +- Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15]. |
| 20 | +- Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30]. |
| 21 | +The array has become sorted, hence we return true. |
| 22 | +Note that there may be other sequences of operations which also sort the array. |
| 23 | +
|
| 24 | +Example 2: |
| 25 | +Input: nums = [1,2,3,4,5] |
| 26 | +Output: true |
| 27 | +Explanation: The array is already sorted, hence we return true. |
| 28 | +
|
| 29 | +Example 3: |
| 30 | +Input: nums = [3,16,8,4,2] |
| 31 | +Output: false |
| 32 | +Explanation: It can be shown that it is not possible to sort the input array using any number of operations. |
| 33 | +
|
| 34 | +Constraints: |
| 35 | +* 1 <= nums.length <= 100 |
| 36 | +* 1 <= nums[i] <= 28 |
| 37 | +=end |
| 38 | + |
| 39 | +# @param {Integer[]} nums |
| 40 | +# @return {Boolean} |
| 41 | +def can_sort_array(nums) |
| 42 | + nums.chunk { _1.digits(2).sum }.each_cons(2).all? { |(_, a), (_, b)| a.max <= b.min } |
| 43 | +end |
| 44 | + |
| 45 | +# **************** # |
| 46 | +# TEST # |
| 47 | +# **************** # |
| 48 | + |
| 49 | +require "test/unit" |
| 50 | +class Test_can_sort_array < Test::Unit::TestCase |
| 51 | + def test_ |
| 52 | + assert_equal true, can_sort_array([8, 4, 2, 30, 15]) |
| 53 | + assert_equal true, can_sort_array([1, 2, 3, 4, 5]) |
| 54 | + assert_equal false, can_sort_array([3, 16, 8, 4, 2]) |
| 55 | + end |
| 56 | +end |
0 commit comments