aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2024-08-03 00:09:09 -0600
committerJack Sangdahl <[email protected]>2024-08-03 00:09:09 -0600
commita80fa577d76782c889e35b54a17d6e5c2c9d88b4 (patch)
tree8fdd77eb1a78b639d32a5b7d744988158e5a2ce5
parent3dd518795de5a8372b39a6f6984acb0b2d5d5dbc (diff)
downloadleetcode-a80fa577d76782c889e35b54a17d6e5c2c9d88b4.tar.gz
leetcode-a80fa577d76782c889e35b54a17d6e5c2c9d88b4.zip
1460. make two arrays equal by reversing subarrays
-rw-r--r--make_two_arr_eq_reverse.c34
-rw-r--r--make_two_arr_eq_reverse.py31
2 files changed, 65 insertions, 0 deletions
diff --git a/make_two_arr_eq_reverse.c b/make_two_arr_eq_reverse.c
new file mode 100644
index 0000000..a64f246
--- /dev/null
+++ b/make_two_arr_eq_reverse.c
@@ -0,0 +1,34 @@
+// 1460. Make Two Arrays Equal by Reversing Subarrays
+#include "leetcode.h"
+
+/*
+ * you are given two integer arrays of equal length 'target' and 'arr'. in one
+ * step, you can select any non empty subarray of 'arr' and reverse it. you are
+ * allowed to make any number of steps. return true if you can make 'arr' equal
+ * to 'target' or false otherwise.
+ */
+
+bool canBeEqual(int *target, int targetSize, int *arr, int arrSize) {
+ if (targetSize != arrSize)
+ return false;
+ int cnt[1001] = {0};
+ for (int i = 0; i < targetSize; i++) {
+ cnt[target[i]]++;
+ cnt[arr[i]]--;
+ }
+ for (int i = 0; i < 1001; i++)
+ if (cnt[i])
+ return false;
+ return true;
+}
+
+int main() {
+ int t1[] = {1, 2, 3, 4}, a1[] = {2, 4, 1, 3}, t2[] = {7}, a2[] = {7},
+ t3[] = {3, 7, 9}, a3[] = {3, 7, 11};
+ printf("%d\n",
+ canBeEqual(t1, ARRAY_SIZE(t1), a1, ARRAY_SIZE(a1))); // expect: 1
+ printf("%d\n",
+ canBeEqual(t2, ARRAY_SIZE(t2), a2, ARRAY_SIZE(a2))); // expect: 1
+ printf("%d\n",
+ canBeEqual(t3, ARRAY_SIZE(t3), a3, ARRAY_SIZE(a3))); // expect: 0
+}
diff --git a/make_two_arr_eq_reverse.py b/make_two_arr_eq_reverse.py
new file mode 100644
index 0000000..93b6442
--- /dev/null
+++ b/make_two_arr_eq_reverse.py
@@ -0,0 +1,31 @@
+# 1460. Make Two Arrays Equal by Reversing Subarrays
+from collections import Counter
+
+"""
+you are given two integer arrays of equal length 'target' and 'arr'. in one
+step, you can select any non empty subarray of 'arr' and reverse it. you are
+allowed to make any number of steps. return true if you can make 'arr' equal
+to 'target' or false otherwise.
+"""
+
+
+class Solution(object):
+ def canBeEqual(self, target, arr):
+ """
+ :type target: List[int]
+ :type arr: List[int]
+ :rtype: bool
+ """
+ if len(target) != len(arr):
+ return False
+ cnt = Counter(target)
+ for num in arr:
+ cnt[num] -= 1
+ return all(cnt[num] == 0 for num in cnt)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.canBeEqual(target=[1, 2, 3, 4], arr=[2, 4, 1, 3]))
+ print(obj.canBeEqual(target=[7], arr=[7]))
+ print(obj.canBeEqual(target=[3, 7, 9], arr=[3, 7, 11]))