Problem 1460

Abstract / Summary

Check if both arrays have the same elements with the same counts before making them equal by reversing subarrays.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1460.py

class Solution:
    def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
        return sorted(target) == sorted(arr)
3 lines | 133 bytes | submitted January 11, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 76% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a single method canBeEqual that determines whether two integer arrays can be made identical by reordering their elements. The approach relies on sorting both input collections and then checking for exact equality of the resulting sequences. By leveraging Python’s built-in sorted function, the solution abstracts away the low-level details of the sorting algorithm while ensuring a concise and readable implementation.

Key Steps

The core logic consists of three conceptual actions: receiving the inputs, sorting each list, and comparing the sorted results. The following snippet isolates the sorting and comparison step that drives the decision:

sorted_target = sorted(target)
sorted_arr = sorted(arr)
return sorted_target == sorted_arr

The method returns the boolean outcome of the equality test directly, eliminating the need for additional conditional structures.

Edge Cases Handled

When both target and arr are empty, the sorted calls produce empty lists, and the equality comparison yields True, correctly reflecting that two empty collections are trivially equal after any reordering.

If the arrays contain duplicate values, the sorting process groups identical elements together, guaranteeing that the multiplicity of each value is respected during the final comparison. For example, [2, 1, 2] and [2, 2, 1] both become [1, 2, 2] after sorting, leading to a True result.

When the lengths differ, the sorted lists will have different sizes, and the equality operator will immediately evaluate to False. This covers scenarios where one list has extra or missing elements, regardless of the actual values.

Performance Optimizations

The implementation benefits from Python’s highly tuned sorting routine, which adapts to the characteristics of the input data. The underlying algorithm (Timsort) excels with partially ordered sequences, reducing the amount of work required for nearly sorted inputs. By calling sorted separately on each list, the code allows the interpreter to allocate memory for the new sorted sequences in a single pass, avoiding repeated allocations or manual element swaps.

Returning the result of the equality check directly also eliminates any unnecessary temporary variables or branching logic, keeping the execution path minimal. This direct return pattern ensures that the interpreter can short-circuit the comparison as soon as a mismatch is detected, providing an early exit in many practical cases.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two boxes filled with colorful blocks. One box is the target box, and the other one is the box you are holding. You want to see if both boxes have exactly the same set of blocks inside, even if they are all mixed up. To find out, you decide to lay all the blocks from the first box out in a straight line from smallest to biggest. Then, you do the exact same thing with the blocks from your box. Once they are both lined up in order from smallest to biggest, you just look at them side by side. If the lines look like perfect twins, you know you have the same set of blocks.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.85 | σ = 1.46

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java C Go PHP Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
haoel C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
trung-hn Python
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
trung-hn Python
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
36 links | 21 authors | 11 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 easy 1 hard
5 solutions   January 11, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality