
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Reverse Sublist to Form Another List in Python
Suppose we have two lists of numbers called A, and B. We have to take some sublist in A and reverse it. Then check whether it is possible to turn A into B or not. We can take sublist and reverse it any number of times.
So, if the input is like A = [2, 3, 4, 9, 10], B = [4, 3, 2, 10, 9], then the output will be True as we can reverse [2,3,4] and [9,10].
To solve this, we will follow these steps −
- res := a map, initially empty
- for each n in nums, do
- res[n] := res[n] + 1
- for each t in target, do
- res[t] := res[t] - 1
- return true when all elements in the values of res is same as 0.
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict class Solution: def solve(self, nums, target): res = defaultdict(int) for n in nums: res[n] += 1 for t in target: res[t] -= 1 return all(n == 0 for n in res.values()) ob = Solution() A = [2, 3, 4, 9, 10] B = [4, 3, 2, 10, 9] print(ob.solve(A, B))
Input
[2, 3, 4, 9, 10], [4, 3, 2, 10, 9]
Output
True
Advertisements