Make Two Arrays Equal by Reversing Subarrays

easy hashing frequency count array

Problem

You are given two integer arrays of equal length target and arr. In one step you may pick any non-empty subarray of arr and reverse it, and you may do this any number of times. Return true if you can make arr equal to target, otherwise false. Reversing subarrays can reorder the elements arbitrarily, so the answer is true exactly when both arrays contain the same values with the same multiplicities.

Inputtarget = [1,2,3,4], arr = [2,4,1,3]
Outputtrue
Both arrays are permutations of {1,2,3,4}, so a sequence of reversals turns arr into target.
Inputtarget = [3,7,9], arr = [3,7,11]
Outputfalse
arr has an 11 but no 9, so no amount of reversing can match target.

def can_be_equal(target, arr):
    count = {}
    for v in target:
        count[v] = count.get(v, 0) + 1
    for v in arr:
        if v not in count or count[v] == 0:
            return False
        count[v] -= 1
    return True
function canBeEqual(target, arr) {
  const count = new Map();
  for (const v of target) {
    count.set(v, (count.get(v) || 0) + 1);
  }
  for (const v of arr) {
    if (!count.get(v)) return false;
    count.set(v, count.get(v) - 1);
  }
  return true;
}
boolean canBeEqual(int[] target, int[] arr) {
    Map<Integer, Integer> count = new HashMap<>();
    for (int v : target) {
        count.merge(v, 1, Integer::sum);
    }
    for (int v : arr) {
        int c = count.getOrDefault(v, 0);
        if (c == 0) return false;
        count.put(v, c - 1);
    }
    return true;
}
bool canBeEqual(vector<int>& target, vector<int>& arr) {
    unordered_map<int, int> count;
    for (int v : target) {
        count[v]++;
    }
    for (int v : arr) {
        if (count[v] == 0) return false;
        count[v]--;
    }
    return true;
}
Time: O(n) Space: O(n)