Tutorialspoint
Problem
Solution
Submissions

Check if Two Arrays are Equal

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 8

Write a JavaScript program to determine if two arrays are equal. Two arrays are considered equal if they contain the same elements in the same order. The function should handle arrays of different data types including numbers, strings, and nested arrays.

Example 1
  • Input: arr1 = [1, 2, 3], arr2 = [1, 2, 3]
  • Output: true
  • Explanation:
    • First array is [1, 2, 3].
    • Second array is [1, 2, 3].
    • Both arrays have same length (3).
    • All corresponding elements are equal.
    • Therefore, arrays are equal.
Example 2
  • Input: arr1 = [1, 2, 3], arr2 = [1, 3, 2]
  • Output: false
  • Explanation:
    • First array is [1, 2, 3].
    • Second array is [1, 3, 2].
    • Both arrays have same length (3).
    • Elements at index 1 and 2 are different.
    • arr1[1] = 2, arr2[1] = 3 (not equal).
    • Therefore, arrays are not equal.
Constraints
  • 0 ≤ arr1.length, arr2.length ≤ 1000
  • Arrays can contain numbers, strings, or nested arrays
  • Comparison should be done element by element
  • Arrays must have same length and same order to be equal
  • Time Complexity: O(n) where n is the length of arrays
  • Space Complexity: O(1)
ArraysCapgeminiAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • First check if both arrays have the same length
  • Iterate through both arrays simultaneously
  • Compare each pair of corresponding elements
  • Handle different data types appropriately
  • Return false immediately if any pair doesn't match

Steps to solve by this approach:

 Step 1: Compare the lengths of both input arrays.
 Step 2: If lengths are different, immediately return false.
 Step 3: Initialize a loop to iterate through both arrays simultaneously.
 Step 4: Compare each pair of corresponding elements at the same index.
 Step 5: If any pair of elements is not equal, return false immediately.
 Step 6: Continue comparison until all elements are checked.
 Step 7: If all elements match, return true indicating arrays are equal.

Submitted Code :