Check if Two Arrays Are Equal: 3 Approaches Explained
Three approaches to check if two arrays are equal: sort-and-compare, frequency count, and direct match, with working code and complexity analysis.
Two arrays are equal if they contain the same elements, but whether order matters changes which algorithm you need.
What “Equal” Means Depends on the Problem
Array equality has two distinct definitions, and mixing them up produces wrong answers.
Order-sensitive equality: [1, 2, 3] equals [1, 2, 3] but not [3, 1, 2]. Every element must appear at the same position in both arrays. This is what Python’s == operator checks for lists.
Order-insensitive equality: [1, 2, 3] and [3, 1, 2] are equal because they contain the same multiset of values. Position does not matter; only the collection of elements does.
Placement test problems usually specify one. Phrases like “same elements regardless of order” or “same values, any arrangement” signal order-insensitive equality. Phrases like “same sequence” or “identical arrays” signal order-sensitive equality. When the problem shows a sample input where [1, 2, 3] and [3, 2, 1] both produce “Same”, you know order does not matter.
The three approaches below each target one or both definitions.
Approach 1: Sort Both Arrays, Then Compare
Sort each array, then check whether the sorted versions are identical element by element. Sorting makes both arrays canonical: if they contain the same multiset of values, their sorted forms will be identical.
Python:
def arrays_equal_sorted(a, b):
if len(a) != len(b):
return False
return sorted(a) == sorted(b)
a = [1, 2, 3]
b = [3, 1, 2]
print("Same" if arrays_equal_sorted(a, b) else "Not Same")
# Output: Same
a2 = [1, 2, 3]
b2 = [1, 2, 4]
print("Same" if arrays_equal_sorted(a2, b2) else "Not Same")
# Output: Not Same
Java:
import java.util.Arrays;
public class ArrayEquality {
public static boolean arraysEqualSorted(int[] a, int[] b) {
if (a.length != b.length) return false;
int[] aCopy = Arrays.copyOf(a, a.length);
int[] bCopy = Arrays.copyOf(b, b.length);
Arrays.sort(aCopy);
Arrays.sort(bCopy);
return Arrays.equals(aCopy, bCopy);
}
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {3, 1, 2};
System.out.println(arraysEqualSorted(a, b) ? "Same" : "Not Same");
}
}
C++:
#include <algorithm>
#include <iostream>
#include <vector>
bool arraysEqualSorted(std::vector<int> a, std::vector<int> b) {
if (a.size() != b.size()) return false;
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
return a == b;
}
int main() {
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {3, 1, 2};
std::cout << (arraysEqualSorted(a, b) ? "Same" : "Not Same") << std::endl;
return 0;
}
A note on the Java version: Arrays.sort() modifies the original array in place. The code above uses Arrays.copyOf() to sort copies, leaving the caller’s arrays unchanged. Skipping the copy step is a silent mutation bug that shows up in multi-step interview problems where you reuse the array later.
Time complexity: O(n log n) from sorting. Space complexity: O(n) because sorted() in Python and Arrays.copyOf() in Java each allocate a new copy; the C++ version passes by value so also O(n).
Approach 2: Frequency Count with a Hash Map
Count how many times each element appears in each array. If every element has the same count in both arrays, they are equal. This runs in O(n) time at the cost of O(n) auxiliary space for the hash map.
Python’s collections.Counter makes this compact:
from collections import Counter
def arrays_equal_counter(a, b):
if len(a) != len(b):
return False
return Counter(a) == Counter(b)
a = [1, 1, 2]
b = [1, 2, 1]
print("Same" if arrays_equal_counter(a, b) else "Not Same")
# Output: Same
a2 = [1, 1, 2]
b2 = [1, 2, 2]
print("Same" if arrays_equal_counter(a2, b2) else "Not Same")
# Output: Not Same
Java (manual HashMap):
import java.util.HashMap;
public class ArrayEqualityHash {
public static boolean arraysEqualHash(int[] a, int[] b) {
if (a.length != b.length) return false;
HashMap<Integer, Integer> freq = new HashMap<>();
for (int x : a) freq.merge(x, 1, Integer::sum);
for (int x : b) {
if (!freq.containsKey(x)) return false;
int updated = freq.get(x) - 1;
if (updated == 0) freq.remove(x);
else freq.put(x, updated);
}
return freq.isEmpty();
}
}
The key advantage over sorting: you get O(n) time instead of O(n log n). The trade-off is O(n) extra space for the hash map. For large arrays where time is the bottleneck and memory is available, this is the better choice. The Java HashMap.merge() call handles the count increment in one line; the equivalent in C++ is std::unordered_map.
This approach handles duplicates correctly. [1, 1, 2] is not equal to [1, 2, 2] even though both contain elements 1 and 2, because 1 appears twice in the first array and once in the second.
Approach 3: Direct Element-by-Element Match
If the problem defines equality as order-sensitive, skip sorting entirely. Compare each index position directly. This runs in O(n) time and O(1) space, making it the most efficient approach when order is fixed.
Python:
def arrays_equal_direct(a, b):
if len(a) != len(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
return False
return True
# Python's built-in == on lists does the same thing
def arrays_equal_builtin(a, b):
return a == b
Python’s == operator on lists is order-sensitive by default. [1, 2, 3] == [3, 2, 1] evaluates to False. This is what you want for order-sensitive problems.
In C++, std::equal from <algorithm> handles this in one line:
#include <algorithm>
#include <vector>
bool arraysEqualDirect(const std::vector<int>& a, const std::vector<int>& b) {
return a.size() == b.size() &&
std::equal(a.begin(), a.end(), b.begin());
}
std::equal compares element by element and returns true only if every corresponding pair matches. Because both arrays are passed by const reference, no copies are made.
Complexity at a Glance
| Approach | Time | Space | Handles order-insensitive? |
|---|---|---|---|
| Sort and compare | O(n log n) | O(n) | Yes |
| Frequency count (hash map) | O(n) | O(n) | Yes |
| Direct element match | O(n) | O(1) | No |
The sort approach is easiest to reason about and write correctly in an interview setting. The frequency count approach is faster for large inputs. Direct comparison is the right call when the problem specifies that order matters and you need to avoid allocating extra memory.
For a deeper look at why the hash map trades space for time and how to reason about that trade-off in general, the space complexity guide covers the derivation framework that AMCAT Automata questions test.
Edge Cases to Include in Your Test Suite
Writing a correct solution for the happy path and leaving out edge cases is one of the most common reasons placement coding submissions lose marks. For the array equality problem, run your implementation against at least these inputs before submitting:
- Different lengths:
[1, 2, 3]vs[1, 2]. The length check at the start catches this before any looping. Expected output: “Not Same”. - Empty arrays:
[]vs[]. Both have length 0, so the length check passes and the comparison returns “Same” immediately. All three approaches handle this correctly. - Single element, equal:
[5]vs[5]. Expected output: “Same”. - Single element, not equal:
[5]vs[7]. Expected output: “Not Same”. - Duplicates, same count:
[1, 1, 2]vs[1, 2, 1]. Expected output: “Same” (order-insensitive) or “Not Same” (order-sensitive, because index 2 differs). - Duplicates, different count:
[1, 1, 2]vs[1, 2, 2]. Expected output: “Not Same” under both definitions. - All elements identical:
[3, 3, 3]vs[3, 3, 3]. Expected output: “Same”.
The hash-map pattern used in Approach 2 above extends naturally to related array problems. The symmetric pairs program uses the same frequency-lookup logic to check whether a pair (a[i], a[j]) has a mirror entry in the array. A different kind of array scan, where a single position balances the entire array, appears in the equilibrium index problem. Both problems are worth pairing with array equality in a revision session.
The Complexity at a Glance table above captures the most common interview follow-up after a working solution: “Can you do it faster?” The frequency count approach drops O(n log n) sorting time to O(n) by using O(n) extra memory for the hash map. That space-time swap is the kind of reasoning TinkerLLM is built for: a Python sandbox where you can run all three implementations side by side, time them, and see the difference on inputs of different sizes. First experiment takes about ten minutes; ₹299 to start.
Primary sources
Frequently asked questions
Do the arrays have to be in the same order to be considered equal?
It depends on the problem statement. If the problem asks for order-insensitive equality, two arrays with the same elements in any order are equal. If order matters, [1, 2, 3] and [3, 2, 1] are not equal. Approach 1 and Approach 2 in this guide both handle order-insensitive equality; Approach 3 handles order-sensitive equality only.
What is the time complexity of checking array equality by sorting?
O(n log n), because sorting dominates the comparison step. After sorting both arrays, the element-by-element comparison runs in O(n), but the sort is the bottleneck. If you need O(n) time, use the frequency count approach instead.
Does the hash map approach handle duplicate elements correctly?
Yes. The frequency count approach counts how many times each element appears in each array. So [1, 1, 2] and [1, 2, 2] are correctly identified as not equal: element 1 appears twice in the first array and once in the second, so the counts differ.
What if the two arrays have different lengths?
A length check at the start returns Not Same immediately, in O(1) time. All three approaches in this guide perform this check before any looping begins. Two arrays of different lengths cannot be equal under either definition.
Which approach is fastest for large arrays?
The frequency count (hash map) approach at O(n) time is the fastest for large inputs. The sort-and-compare approach runs in O(n log n). For order-sensitive equality with fixed input order, direct comparison is also O(n) and uses only O(1) space, making it the best choice when memory is constrained.
Can Python's == operator compare arrays for equality?
Yes, but Python list == is order-sensitive. It returns False for [1, 2, 3] == [3, 2, 1] even though both contain the same elements. To compare order-insensitively in Python, use sorted(a) == sorted(b) or Counter(a) == Counter(b).
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)