Skip to content

1460. Make Two Arrays Equal by Reversing Subarrays #229

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

  1. Check if both arrays have the same elements with the same frequency. If they do, it means one array can be transformed into the other by reversing subarrays. Sorting both arrays and comparing them is an easy way to achieve this.

Let's implement this solution in PHP: 1460. Make Two Arrays Equal by Reversing Subarrays

<?php
function canBeEqual($target, $arr) {
    // Sort both arrays
    sort($target);
    sort($arr);
    
    // Compare the sorted arrays
    return $target == $arr;
}

// Test cases
$target1 = [1, 2, 3, 4];
$arr1 = [2, 4, 1, 3];
echo canBeEqual($target1, $arr1) ? 'true' : 'false'; // Output: true

$target2 = [7];
$arr2 = [7]…

Replies: 1 comment 3 replies

Comment options

mah-shamim
Aug 3, 2024
Maintainer Author

You must be logged in to vote
3 replies
@kovatz
Comment options

kovatz Aug 3, 2024
Collaborator

@topugit
Comment options

topugit Aug 3, 2024
Collaborator

@basharul-siddike
Comment options

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
4 participants