Make Two Arrays Equal by Reversing Subarrays - Leetcode 1460 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·1y ago

Key Takeaways

Solves Make Two Arrays Equal by Reversing Subarrays problem on Leetcode using Python

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem make two arrays equal by reversing subarrays so this is an easy problem and at first glance you might be wondering why it seems a little difficult for an easy problem but I'm going to show you that there's a pretty simple way to think about this problem basically the idea is we're given two arrays they're always going to be of the same length so we don't have to worry about that but we basically want to take elements I guess they say the second array and we can choose any sub array so it could start from the beginning or it could go through the middle whatever any subarray and then reverse those numbers so we want to know can we turn this array into the original array and this example we actually can so it's not super obvious how but firstly we take these first three elements and reverse them I think then we get 1 4 2 3 and just so you know the target array is just 1 2 3 4 so we're trying to kind of get it in sorted order at least in this example so next I think we can swap these two and then we'll get 1 2 4 3 and then we can swap the last two and then we'll have 1 2 3 4 so it seems kind of difficult I mean to brute force it there's going to be a lot of possible subarrays but when you're clever you can think about it in terms of this we just want every single element let's start with one we want one to go in the beginning we want to get it over here doesn't really matter where the rest of the elements are after that we want to get two in the second position then we want to get three in the third position and four in the last position the easiest way to do this is just take this element and just keep swapping it with its left neighbor so that would end up looking something like this 1 2 4 and then three so now two is already in the right spot and then we could swap these two the way I'm thinking about this is definitely not going to minimize the number of like reversing subarrays or anything like that but we're not asked to minimize it we just want to know can we actually form the target array so at this point it's not a matter of how we swap the elements it's only a matter of do we actually have all the elements in the second array that we have in the first array basically we're asking is regardless of the order of these two arrays are these arrays equal I'm sure you already know this cuz you've definitely gone through the ne code 150 list and you're probably tired of me even mentioning this but once again NE code 150 I always talk about it because it always comes up this is pretty much the exact same problem as valid anagram and so the solution is going to be similar I'll quickly mention the trivial solution we can just take both arrays and sort them which is going to be n log n time both of the arrays are of equal length and then after we sort them we can just check if they are both equal to each other that's not the most efficient solution though the most efficient solution is going to be about counting the elements in each array because we could technically have duplicates we might have multiple fours we might have multiple ones so we want to know does the count of every single element in each array match the count in the other array so counting is generally done with a hashmap so that's how I'm going to do this so if we were to create a hashmap of both of these we' see that one has a count of one in this case two has a count of one three has a count of one and four has a count of one as well obviously we could have you know some elements with multiple like we could have three twos we could have four threes something like that and then we'd have the second hashmap and we would just want to check are the elements in every single hashmap equal and also that there aren't any keys in the other hashmap that don't exist in both hashmaps visually I think this is pretty simple to understand but coding it up might be a little bit tricky so let's get into that this is going to be a linear time solution though because we're just going to be iterating over both inputs and then building the hashmap hash maps have constant operations for every single thing so that's why it's efficient and space complexity is going to be for the hashmap as well so first let me actually just show you the most trivial way to code this up python makes it so easy so we can do something called a counter on the target array and we can do counter on the second array this is basically building a hashmap counting the occurrences of each element and for us to check if these are exactly equal well python makes that pretty easy too just use the equal sign so we can just return this so that's the oneliner solution to this I know you might consider it cheating but I do feel it's worth mentioning because it does work but maybe in a real interview you will be asked to elaborate on these you might be asked to implement the counter yourself so let's actually get into that let's say we have count one and count 2 and both of these are going to be hashmaps and they're going to be default dictionaries so the default value is going to be an integer that's going to make things slightly easier for us so what we're going to do is iterate over both arrays python makes that pretty easy we can iterate over both of them at the same time using something like this for N1 N2 IN Zip the target array and the other array I if you wanted to do this the original way you could do something like this for I in range length of Target because we know both of them are the same and then to get N1 you could just do something like Target at index I to get N2 you could do something like array at indexi so this is equivalent to this this is obviously a little bit shorter you can learn exactly how to do that in my I think python for coding interviews course we just want to take let's say the elements from Target which is going to be N1 is going to correspond to count one so we're going to do this increment it by one same thing for count two we're going to take N2 and increment that by one the reason I made these default dictionaries is here this is basically the same as doing a count one like N1 is equal to itself plus one obviously if the key doesn't exist in the hashmap already with a regular hashmap we would get a key error but with default dictionaries it'll return zero as the default value because we specified it as an integer again I think this this is also covered in Python for coding interviews but now we want to check that both of these are equal the first thing we're going to check is that the length of both of them are equal because even though the length of the input arrays were equal we also want to check that the distinct elements in both of these are also equal now that we've kind of eliminated duplicates so let's check length of count one is not equal to count 2 in that case let's return false otherwise before we're allowed to return true we also have to check that the count of each element is equal so let's just go through all the keys in one of the hashmaps so n in count one and if the count is not equal to the same element in count two then we would return false and the fact that we have the length check up here we'll make sure that if these two hash maps are not equal this will eventually evaluate to false because we know both of the inputs were of the same length so if they have the same number of distinct elements the count of all of them should be equal if they are equal otherwise the count is going to differ at some point and in that case we would return false so if these don't return false we return true and you can see that this will also work but there actually is a way to get this down to just using a single hashmap so let me kind of optimize this just a tiny bit let's just have a single hashmap let's call it count we're going to do the same thing up here but with the first element we're going to increment the count of that with count from the second element with the same hashmap we're actually going to decrement the count so you might be able to see where I'm going with this we don't need the length check anymore but we do need to go through every key in the hashmap and we need to make sure that the length is equal to zero because if it's not equal to zero at any of the keys that means that either we had extra elements in the first Target or we had some extra elements here it could be positive or it could be negative but it should be zero so if it's not zero we would return false otherwise down here we return true so let's just run this and you can see that also works these run times are pretty random all of the solutions I showed you had actually the same time and space complexity obviously this one only used one hashmap but the big o space complexity is still technically the same if you found this helpful check out n code. thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link: https://leetcode.com/problems/make-two-arrays-equal-by-reversing-subarrays/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 4:01 - Coding Explanation leetcode 1460 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

Related Reads

📰
75 Days of Leetcode — Day 4: #238 — Product of Array Except Self
Solve the Product of Array Except Self problem on LeetCode to improve coding skills and learn array manipulation techniques
Medium · AI
📰
I implemented the algorithm that broke the sorting barrier. Dijkstra still wins.
Learn how the author implemented an algorithm that broke the sorting barrier and compare its performance with Dijkstra's algorithm
Medium · Programming
📰
I implemented the algorithm that broke the sorting barrier. Dijkstra still wins.
Implementing an algorithm that breaks the sorting barrier still can't beat Dijkstra's algorithm in practice, highlighting the importance of real-world testing and optimization.
Medium · Python
📰
Practice Algorithms and DS the Structured Way
Learn to practice algorithms and data structures in a structured way to build a mental map of techniques
Medium · Programming

Chapters (3)

Read the problem
0:30 Drawing Explanation
4:01 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →