algoadvance

You are given two integer arrays target and arr of the same length. In one step, you can select any non-empty subarray of arr and reverse it. You need to determine if you can make arr equal to target after performing any number of steps.

Clarifying Questions

  1. Can the arrays contain duplicate elements?
    • Yes, the arrays can contain duplicate elements.
  2. What is the range of the array elements and the length of the arrays?
    • Both arrays will have the same length n, where 1 <= target.length == arr.length <= 1000.
    • The elements of the arrays are integers between 1 and 1000.
  3. Is the order of elements important?
    • No, the order of elements in arr and target is not important since we can reverse any subarray.

Strategy

  1. Key Insight:
    • Since you can reverse any subarray, you have the freedom to rearrange the elements in any order. Therefore, the problem reduces to checking if both arrays have the same elements with the same frequency.
  2. Approach:
    • Use a data structure like a Counter or dictionary to count the frequency of each element in both arrays.
    • Compare the two frequency counts. If they match, return True. Otherwise, return False.

Code

from collections import Counter

def canBeEqual(target, arr):
    return Counter(target) == Counter(arr)

# Example Usage
target = [1, 2, 3, 4]
arr = [2, 4, 1, 3]
print(canBeEqual(target, arr))  # Output: True

target = [7]
arr = [7]
print(canBeEqual(target, arr))  # Output: True

target = [3, 7, 9]
arr = [3, 7, 11]
print(canBeEqual(target, arr))  # Output: False

Time Complexity

Try our interview co-pilot at AlgoAdvance.com