description stringlengths 171 4k | code stringlengths 94 3.98k | normalized_code stringlengths 57 4.99k |
|---|---|---|
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
self.remainSeats = capacity
self.tripsOnBoard = []
trips = sorted(trips, key=lambda trip: trip[1])
for trip in trips:
self.offBoard(trip[1])
if not self.onBoardTrip(trip):
return False
return True
def offBoard(self, currentLocation: int):
trips2OffBoard = [
trip for trip in self.tripsOnBoard if trip[2] <= currentLocation
]
for trip in trips2OffBoard:
self.remainSeats += trip[0]
self.tripsOnBoard = [
trip for trip in self.tripsOnBoard if trip[2] > currentLocation
]
def onBoardTrip(self, trip: List[int]) -> bool:
if trip[0] <= self.remainSeats:
self.remainSeats -= trip[0]
self.tripsOnBoard.append(trip)
return True
else:
return False | CLASS_DEF FUNC_DEF VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR LIST ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER FOR VAR VAR EXPR FUNC_CALL VAR VAR NUMBER IF FUNC_CALL VAR VAR RETURN NUMBER RETURN NUMBER VAR FUNC_DEF VAR ASSIGN VAR VAR VAR VAR VAR NUMBER VAR FOR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR NUMBER VAR FUNC_DEF VAR VAR IF VAR NUMBER VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN NUMBER RETURN NUMBER VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
ma = float("-inf")
trips = sorted(trips, key=lambda v: v[1])
for i in range(len(trips)):
tmp = 0
for j in range(i + 1):
if trips[j][2] > trips[i][1]:
tmp += trips[j][0]
ma = max(tmp, ma)
return ma <= capacity | CLASS_DEF FUNC_DEF VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR NUMBER VAR VAR NUMBER VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR VAR VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
occupied = [(0) for i in range(1001)]
for num_passengers, start_location, end_location in trips:
for i in range(start_location, end_location):
occupied[i] += num_passengers
return max(occupied) <= capacity | CLASS_DEF FUNC_DEF VAR VAR VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR NUMBER FOR VAR VAR VAR VAR FOR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
final = 0
for trip in trips:
final = max(final, trip[2])
people = [0] * (final + 1)
for trip in trips:
for board in range(trip[1], trip[2]):
people[board] += trip[0]
if max(people) > capacity:
return False
else:
return True | CLASS_DEF FUNC_DEF VAR VAR VAR VAR ASSIGN VAR NUMBER FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR VAR FOR VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
trips = sorted(trips, key=lambda x: x[1])
curr = []
for i in trips:
curr.append([i[0], i[2]])
s = 0
for c in curr:
if c[1] <= i[1]:
continue
s += c[0]
if s > capacity:
return False
return True | CLASS_DEF FUNC_DEF VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR LIST FOR VAR VAR EXPR FUNC_CALL VAR LIST VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF VAR NUMBER VAR NUMBER VAR VAR NUMBER IF VAR VAR RETURN NUMBER RETURN NUMBER VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
def car_pooling(trips, capacity):
trips.sort(key=lambda x: x[1])
timeline = {}
for trip in trips:
for t in range(trip[1], trip[2]):
timeline[t] = timeline.get(t, 0) + trip[0]
for t in timeline:
if timeline[t] > capacity:
return False
return True
return car_pooling(trips, capacity) | CLASS_DEF FUNC_DEF VAR VAR VAR VAR FUNC_DEF EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR DICT FOR VAR VAR FOR VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR NUMBER FOR VAR VAR IF VAR VAR VAR RETURN NUMBER RETURN NUMBER RETURN FUNC_CALL VAR VAR VAR VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
trips_pickup = sorted(trips, key=lambda x: x[1])
trips_drop = sorted(trips, key=lambda x: x[2])
passengers = 0
i = 0
j = 0
while i < len(trips):
if trips_pickup[i][1] < trips_drop[j][2]:
passengers += trips_pickup[i][0]
else:
passengers -= trips_drop[j][0]
j += 1
continue
i += 1
if passengers > capacity:
return False
return True | CLASS_DEF FUNC_DEF VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR VAR NUMBER VAR VAR VAR NUMBER VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER IF VAR VAR RETURN NUMBER RETURN NUMBER VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
trips.sort(key=lambda x: x[1])
length = len(trips)
count = 0
queue = []
for trip in trips:
num_passengers, start_location, end_location = trip
while queue and queue[0][2] <= start_location:
count -= queue[0][0]
queue = queue[1:]
queue.append(trip)
queue.sort(key=lambda x: x[2])
count += num_passengers
if count > capacity:
return False
return True | CLASS_DEF FUNC_DEF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR LIST FOR VAR VAR ASSIGN VAR VAR VAR VAR WHILE VAR VAR NUMBER NUMBER VAR VAR VAR NUMBER NUMBER ASSIGN VAR VAR NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR NUMBER VAR VAR IF VAR VAR RETURN NUMBER RETURN NUMBER VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
d = {}
for i in trips:
for j in range(i[1] + 1, i[2] + 1):
if j not in d:
d[j] = i[0]
else:
d[j] += i[0]
for i in d:
if d[i] > capacity:
return 0
return 1 | CLASS_DEF FUNC_DEF VAR VAR VAR VAR ASSIGN VAR DICT FOR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER BIN_OP VAR NUMBER NUMBER IF VAR VAR ASSIGN VAR VAR VAR NUMBER VAR VAR VAR NUMBER FOR VAR VAR IF VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
if not trips:
return True
firstStop = 1001
lastStop = -1
for trip in trips:
firstStop = min(firstStop, trip[1])
lastStop = max(lastStop, trip[2])
stops = [0] * (lastStop - firstStop + 1)
for trip in trips:
for i in range(trip[1], trip[2]):
stops[i - firstStop] += trip[0]
if stops[i - firstStop] > capacity:
return False
return True | CLASS_DEF FUNC_DEF VAR VAR VAR VAR IF VAR RETURN NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP VAR VAR NUMBER FOR VAR VAR FOR VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER VAR BIN_OP VAR VAR VAR NUMBER IF VAR BIN_OP VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
if len(trips) <= 0:
return False
trips.sort(key=lambda x: x[1])
stack = []
if trips[0][0] > capacity:
return False
else:
stack.append(0)
capacity -= trips[0][0]
for i in range(1, len(trips)):
n = 0
while stack and n < len(stack):
if trips[i][1] >= trips[stack[n]][2]:
capacity += trips[stack[n]][0]
stack.pop(n)
else:
n += 1
if trips[i][0] <= capacity:
capacity -= trips[i][0]
elif trips[i][0] > capacity:
return False
stack.append(i)
return True | CLASS_DEF FUNC_DEF VAR VAR VAR VAR IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR LIST IF VAR NUMBER NUMBER VAR RETURN NUMBER EXPR FUNC_CALL VAR NUMBER VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR NUMBER WHILE VAR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR VAR VAR NUMBER VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR NUMBER IF VAR VAR NUMBER VAR VAR VAR VAR NUMBER IF VAR VAR NUMBER VAR RETURN NUMBER EXPR FUNC_CALL VAR VAR RETURN NUMBER VAR |
The aliens living in outer space are very advanced in technology,
intelligence and everything, except one, and that is Cooking.
Each year they spend millions of dollars in research, to crack famous recipes prepared by humans.
Recently they came to know about Khana-Academy,
a non-profit organization streaming free cooking lesson videos on earth.
There are N recipes,
numbered 1 to N, and the video of the i^{th} recipe is live in the time interval [S_{i}, E_{i}].
An alien can visit earth but can not survive for more than just a small moment (earth is so advanced in pollution).
An alien visits the earth at an integer time t and instantly downloads the complete video of all the lessons
that are live at that moment of time t and leaves earth immediately.
You are given the visiting times of a small group of K aliens.
Find the number of different recipes aliens can learn by watching the downloaded videos.
Not just one group of aliens, there are Q such groups,
so you have to find the answer for each of these Q groups.
------ Input ------
The first line has an integer N.
Each of the following N lines has two integers S_{i} E_{i}.
The next line has an integer Q, the number of groups.
Each of the following Q lines has information of a group of aliens.
The first integer is K, the number of aliens in that group, followed by K integers in the same line,
the integer visiting times t of the aliens.
1 ≤ N ≤ 100000 (10^{5})
1 ≤ Q ≤ 5000 (5 · 10^{3})
1 ≤ K ≤ 20
1 ≤ S_{i}, E_{i}, t ≤ 1000000000 (10^{9})
S_{i} < E_{i}
------ Output ------
For each of the Q groups, output the number of different recipes that group of aliens can learn by watching the downloaded videos.
------ Example ------
Input:
4
1 4
3 10
2 6
5 8
3
1 5
2 2 6
3 1 10 9
Output:
3
4
2
Explanation:
Given videos of 4 recipes in the following closed intervals.
1. [ 1 , 4 ]
2. [ 3 , 10 ]
3. [ 2 , 6 ]
4. [ 5 , 8 ]
In the first query, only one alien arrives at t = 5 and can download 3 recipes 2, 3, 4.
In the second query, two aliens arrive at t = 2 and 6. They can learn all the 4 recipes.
In the third query, three aliens arrive at t = 1, 10 and 9. They can learn only two recipes, 1 and 2. | class FenwickTree:
def __init__(self, size):
self.nodes = [0] * (size + 1)
def get(self, index):
a = self.nodes
s = 0
i = index + 1
while i > 0:
s += a[i]
i -= i & -i
return s
def add(self, index, value):
a = self.nodes
n = len(a)
i = index + 1
while i < n:
a[i] += value
i += i & -i
BEGIN, QUERY, END = 1, 2, 3
def timestampCompressingMap(events):
nextIdx = 0
lookup = {}
for t, _, _ in events:
if t not in lookup:
lookup[t] = nextIdx
nextIdx += 1
return lookup
events = []
for intervalIdx in range(int(input())):
begin, end = map(int, input().split())
events.append((begin, BEGIN, None))
events.append((end, END, begin))
nQueries = int(input())
for queryIdx in range(nQueries):
for query in map(int, input().split()[1:]):
events.append((query, QUERY, queryIdx))
events = sorted(events)
compress = timestampCompressingMap(events)
def compressEvent(event):
t, what, arg = event
return compress[t], what, compress[arg] if what == END else arg
prefixSum = FenwickTree(len(compress))
queryTotal = [0] * nQueries
lastQuery = [None] * nQueries
for t, what, arg in map(compressEvent, events):
if what == BEGIN:
prefixSum.add(t, 1)
elif what == END:
begin = arg
prefixSum.add(begin, -1)
elif what == QUERY:
queryIdx = arg
queryTotal[queryIdx] += prefixSum.get(t)
if lastQuery[queryIdx] != None:
queryTotal[queryIdx] -= prefixSum.get(lastQuery[queryIdx])
lastQuery[queryIdx] = t
for result in queryTotal:
print(result) | CLASS_DEF FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER VAR VAR VAR VAR BIN_OP VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR VAR VAR VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR NUMBER NUMBER NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR DICT FOR VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR NUMBER RETURN VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR NONE EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR VAR VAR VAR RETURN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR BIN_OP LIST NONE VAR FOR VAR VAR VAR FUNC_CALL VAR VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR NUMBER IF VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR NUMBER IF VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR IF VAR VAR NONE VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR FOR VAR VAR EXPR FUNC_CALL VAR VAR |
The aliens living in outer space are very advanced in technology,
intelligence and everything, except one, and that is Cooking.
Each year they spend millions of dollars in research, to crack famous recipes prepared by humans.
Recently they came to know about Khana-Academy,
a non-profit organization streaming free cooking lesson videos on earth.
There are N recipes,
numbered 1 to N, and the video of the i^{th} recipe is live in the time interval [S_{i}, E_{i}].
An alien can visit earth but can not survive for more than just a small moment (earth is so advanced in pollution).
An alien visits the earth at an integer time t and instantly downloads the complete video of all the lessons
that are live at that moment of time t and leaves earth immediately.
You are given the visiting times of a small group of K aliens.
Find the number of different recipes aliens can learn by watching the downloaded videos.
Not just one group of aliens, there are Q such groups,
so you have to find the answer for each of these Q groups.
------ Input ------
The first line has an integer N.
Each of the following N lines has two integers S_{i} E_{i}.
The next line has an integer Q, the number of groups.
Each of the following Q lines has information of a group of aliens.
The first integer is K, the number of aliens in that group, followed by K integers in the same line,
the integer visiting times t of the aliens.
1 ≤ N ≤ 100000 (10^{5})
1 ≤ Q ≤ 5000 (5 · 10^{3})
1 ≤ K ≤ 20
1 ≤ S_{i}, E_{i}, t ≤ 1000000000 (10^{9})
S_{i} < E_{i}
------ Output ------
For each of the Q groups, output the number of different recipes that group of aliens can learn by watching the downloaded videos.
------ Example ------
Input:
4
1 4
3 10
2 6
5 8
3
1 5
2 2 6
3 1 10 9
Output:
3
4
2
Explanation:
Given videos of 4 recipes in the following closed intervals.
1. [ 1 , 4 ]
2. [ 3 , 10 ]
3. [ 2 , 6 ]
4. [ 5 , 8 ]
In the first query, only one alien arrives at t = 5 and can download 3 recipes 2, 3, 4.
In the second query, two aliens arrive at t = 2 and 6. They can learn all the 4 recipes.
In the third query, three aliens arrive at t = 1, 10 and 9. They can learn only two recipes, 1 and 2. | def give_index(time_stamp):
nextind = 0
res = {}
for t, check, _ in time_stamp:
if check != 2 and t not in res:
res[t] = nextind
nextind += 1
return res
def add_sum(tree, index, value):
while index < len(tree):
tree[index] += value
index += index & -index
def give_sum(tree, index):
res = 0
while index > 0:
res += tree[index]
index -= index & -index
return res
no_of_shows = int(input())
time_stamp = []
START, CHECK, END = 0, 1, 2
for i in range(no_of_shows):
start, end = map(int, input().split())
time_stamp.append((start, START, None))
time_stamp.append((end, END, start))
total_queries = int(input())
for i in range(total_queries):
for j in map(int, input().split()[1:]):
time_stamp.append((j, CHECK, i))
time_stamp = sorted(time_stamp)
indexed = give_index(time_stamp)
tree = [0] * (len(indexed) + 1)
final_result = [0] * total_queries
prev_result = [None] * total_queries
for i in time_stamp:
start, value, end = i
if value == START:
add_sum(tree, indexed[start] + 1, 1)
elif value == END:
add_sum(tree, indexed[end] + 1, -1)
else:
query_no = end
final_result[query_no] += give_sum(tree, indexed[start] + 1)
if prev_result[query_no] != None:
final_result[query_no] -= give_sum(tree, prev_result[query_no])
prev_result[query_no] = indexed[start] + 1
for i in final_result:
print(i) | FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR DICT FOR VAR VAR VAR VAR IF VAR NUMBER VAR VAR ASSIGN VAR VAR VAR VAR NUMBER RETURN VAR FUNC_DEF WHILE VAR FUNC_CALL VAR VAR VAR VAR VAR VAR BIN_OP VAR VAR FUNC_DEF ASSIGN VAR NUMBER WHILE VAR NUMBER VAR VAR VAR VAR BIN_OP VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR VAR VAR NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR NONE EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR BIN_OP LIST NONE VAR FOR VAR VAR ASSIGN VAR VAR VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR VAR NUMBER NUMBER IF VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR NUMBER IF VAR VAR NONE VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR NUMBER FOR VAR VAR EXPR FUNC_CALL VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
size = [0]
self.dfs_bst(root, size)
return size[0]
def dfs_bst(self, root, size):
if root == None:
return True, 0, float("inf"), float("-inf")
left_is_bst, left_size, left_min, left_max = self.dfs_bst(root.left, size)
right_is_bst, right_size, right_min, right_max = self.dfs_bst(root.right, size)
if left_is_bst and right_is_bst and left_max < root.data < right_min:
size[0] = max(size[0], left_size + right_size + 1)
return (
True,
left_size + right_size + 1,
min(left_min, root.data),
max(right_max, root.data),
)
else:
return False, 0, 0, 0 | CLASS_DEF FUNC_DEF ASSIGN VAR LIST NUMBER EXPR FUNC_CALL VAR VAR VAR RETURN VAR NUMBER FUNC_DEF IF VAR NONE RETURN NUMBER NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR VAR ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER RETURN NUMBER BIN_OP BIN_OP VAR VAR NUMBER FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR RETURN NUMBER NUMBER NUMBER NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def check(self, root, result):
if root == None:
return ["n", "n"]
a1, b1 = self.check(root.left, result)
a2, b2 = self.check(root.right, result)
if a1 == "f" and b1 == "f" or a2 == "f" and b2 == "f":
return ["f", "f"]
if a1 == "n" and b1 == "n" and a2 == "n" and b2 == "n":
a1 = root.data
b1 = root.data
a2 = root.data
b2 = root.data
result.append(root)
return a1, b2
elif a1 == "n" and b1 == "n":
a1 = root.data
b1 = root.data
if a2 <= root.data:
return ["f", "f"]
else:
result.append(root)
return a1, b2
elif a2 == "n" and b2 == "n":
a2 = root.data
b2 = root.data
if b1 >= root.data:
return ["f", "f"]
else:
result.append(root)
return a1, b2
elif a2 <= root.data or b1 >= root.data:
return ["f", "f"]
else:
result.append(root)
return a1, b2
def cal_size(self, root):
if root == None:
return 0
lh = self.cal_size(root.left)
rh = self.cal_size(root.right)
return lh + rh + 1
def largestBst(self, root):
result = []
a = self.check(root, result)
size = 0
for i in result:
temp = self.cal_size(i)
if temp > size:
size = temp
return size | CLASS_DEF FUNC_DEF IF VAR NONE RETURN LIST STRING STRING ASSIGN VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR IF VAR STRING VAR STRING VAR STRING VAR STRING RETURN LIST STRING STRING IF VAR STRING VAR STRING VAR STRING VAR STRING ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR VAR IF VAR STRING VAR STRING ASSIGN VAR VAR ASSIGN VAR VAR IF VAR VAR RETURN LIST STRING STRING EXPR FUNC_CALL VAR VAR RETURN VAR VAR IF VAR STRING VAR STRING ASSIGN VAR VAR ASSIGN VAR VAR IF VAR VAR RETURN LIST STRING STRING EXPR FUNC_CALL VAR VAR RETURN VAR VAR IF VAR VAR VAR VAR RETURN LIST STRING STRING EXPR FUNC_CALL VAR VAR RETURN VAR VAR FUNC_DEF IF VAR NONE RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN BIN_OP BIN_OP VAR VAR NUMBER FUNC_DEF ASSIGN VAR LIST ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def solve(self, root, Min, Max, res):
if root.left is None and root.right is None:
Min[0] = root.data
Max[0] = root.data
res[0] = max(res[0], 1)
return 1
ans1 = 0
min1 = float("inf")
max1 = float("-inf")
if root.left is not None:
count = self.solve(root.left, Min, Max, res)
if count != -1 and Max[0] < root.data:
ans1 = count
else:
ans1 = -1
min1 = Min[0]
max1 = Max[0]
ans2 = 0
if root.right is not None:
count = self.solve(root.right, Min, Max, res)
if count != -1 and Min[0] > root.data:
ans2 = count
else:
ans2 = -1
Min[0] = min(Min[0], min1, root.data)
Max[0] = max(Max[0], max1, root.data)
if ans1 != -1 and ans2 != -1:
res[0] = max(res[0], ans1 + ans2 + 1)
return ans1 + ans2 + 1
return -1
def largestBst(self, root):
res = [0]
self.solve(root, [float("inf")], [float("-inf")], res)
return res[0] | CLASS_DEF FUNC_DEF IF VAR NONE VAR NONE ASSIGN VAR NUMBER VAR ASSIGN VAR NUMBER VAR ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER NUMBER RETURN NUMBER ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR STRING IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR NUMBER VAR NUMBER VAR ASSIGN VAR VAR ASSIGN VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR NUMBER VAR NUMBER VAR ASSIGN VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR VAR ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR VAR IF VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER RETURN BIN_OP BIN_OP VAR VAR NUMBER RETURN NUMBER FUNC_DEF ASSIGN VAR LIST NUMBER EXPR FUNC_CALL VAR VAR LIST FUNC_CALL VAR STRING LIST FUNC_CALL VAR STRING VAR RETURN VAR NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class NodeValue:
def __init__(self, minNode, maxNode, maxSize):
self.minNode = minNode
self.maxNode = maxNode
self.maxSize = maxSize
class Solution:
def largestBst(self, root):
def largestBSTHelper(root):
if not root:
return NodeValue(float("inf"), float("-inf"), 0)
left = largestBSTHelper(root.left)
right = largestBSTHelper(root.right)
if left.maxNode < root.data < right.minNode:
return NodeValue(
min(root.data, left.minNode),
max(root.data, right.maxNode),
left.maxSize + right.maxSize + 1,
)
return NodeValue(
float("-inf"), float("inf"), max(left.maxSize, right.maxSize)
)
return largestBSTHelper(root).maxSize | CLASS_DEF FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR CLASS_DEF FUNC_DEF FUNC_DEF IF VAR RETURN FUNC_CALL VAR FUNC_CALL VAR STRING FUNC_CALL VAR STRING NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN FUNC_CALL VAR FUNC_CALL VAR STRING FUNC_CALL VAR STRING FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def Valid(self, root, left, right):
if not root:
return True
if left and root.data <= left.data:
return False
if right and root.data >= right.data:
return False
return self.Valid(root.left, left, root) and self.Valid(root.right, root, right)
def __init__(self):
self.res = 0
def su(self, root):
if root == None:
return 0
return 1 + self.su(root.left) + self.su(root.right)
def largestBst(self, root):
if not root:
return 0
if self.Valid(root, None, None):
ans = self.su(root)
self.res = max(ans, self.res)
self.largestBst(root.left)
self.largestBst(root.right)
return self.res | CLASS_DEF FUNC_DEF IF VAR RETURN NUMBER IF VAR VAR VAR RETURN NUMBER IF VAR VAR VAR RETURN NUMBER RETURN FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR FUNC_DEF ASSIGN VAR NUMBER FUNC_DEF IF VAR NONE RETURN NUMBER RETURN BIN_OP BIN_OP NUMBER FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR RETURN NUMBER IF FUNC_CALL VAR VAR NONE NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class MyNode:
def __init__(self, size, mn, mx):
self.size = size
self.min = mn
self.max = mx
class Solution:
def dfs(self, node):
if not node:
return MyNode(0, sys.maxsize, -sys.maxsize)
left = self.dfs(node.left)
right = self.dfs(node.right)
if left.max < node.data and node.data < right.min:
return MyNode(
left.size + right.size + 1,
min(left.min, node.data),
max(right.max, node.data),
)
return MyNode(max(left.size, right.size), -sys.maxsize, sys.maxsize)
def largestBst(self, root):
res = self.dfs(root)
return res.size | CLASS_DEF FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR CLASS_DEF FUNC_DEF IF VAR RETURN FUNC_CALL VAR NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR RETURN FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
bestsizes = [0, 0]
def recurDown(root: Node):
nonlocal bestsizes
if not root:
return [0, 0, 0]
if (not root.left) & (not root.right):
return [1, root.data, root.data]
if not root.left:
rightData = recurDown(root.right)
if rightData[0] == -1:
return rightData
if rightData[1] > root.data:
rightData[0] = rightData[0] + 1
rightData[1] = root.data
return rightData
else:
bestsizes.append(rightData[0])
return [-1, 0, 0]
if not root.right:
leftData = recurDown(root.left)
if leftData[0] == -1:
return leftData
if leftData[2] < root.data:
leftData[0] = leftData[0] + 1
leftData[2] = root.data
return leftData
else:
bestsizes.append(leftData[0])
return [-1, 0, 0]
rightData = recurDown(root.right)
leftData = recurDown(root.left)
if rightData[0] != -1 and leftData[0] != -1:
if rightData[1] > root.data and leftData[2] < root.data:
return [rightData[0] + leftData[0] + 1, leftData[1], rightData[2]]
else:
bestsizes.append(rightData[0])
bestsizes.append(leftData[0])
return [-1, 0, 0]
else:
bestsizes.append(rightData[0])
bestsizes.append(leftData[0])
return [-1, 0, 0]
return max(recurDown(root)[0], max(bestsizes)) | CLASS_DEF FUNC_DEF ASSIGN VAR LIST NUMBER NUMBER FUNC_DEF VAR IF VAR RETURN LIST NUMBER NUMBER NUMBER IF BIN_OP VAR VAR RETURN LIST NUMBER VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER RETURN VAR IF VAR NUMBER VAR ASSIGN VAR NUMBER BIN_OP VAR NUMBER NUMBER ASSIGN VAR NUMBER VAR RETURN VAR EXPR FUNC_CALL VAR VAR NUMBER RETURN LIST NUMBER NUMBER NUMBER IF VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER RETURN VAR IF VAR NUMBER VAR ASSIGN VAR NUMBER BIN_OP VAR NUMBER NUMBER ASSIGN VAR NUMBER VAR RETURN VAR EXPR FUNC_CALL VAR VAR NUMBER RETURN LIST NUMBER NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER VAR NUMBER NUMBER IF VAR NUMBER VAR VAR NUMBER VAR RETURN LIST BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER RETURN LIST NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER RETURN LIST NUMBER NUMBER NUMBER RETURN FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
def f_s(root):
if root:
ls, ll, s1 = f_s(root.left)
rl, rs, s2 = f_s(root.right)
if root.data > ll and root.data < rl:
return min(root.data, ls), max(root.data, rs), s1 + s2 + 1
else:
return 0, 10000000, max(s1, s2)
return 10000000, 0, 0
s3, s4, s5 = f_s(root)
return s5 | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN NUMBER NUMBER FUNC_CALL VAR VAR VAR RETURN NUMBER NUMBER NUMBER ASSIGN VAR VAR VAR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
self.res = 1
def dfs(root):
if not root:
return True, 2**31, -2 * 31, 0
if not root.left and not root.right:
return True, root.data, root.data, 1
lbst, lmin, lmax, lcount = dfs(root.left)
rbst, rmin, rmax, rcount = dfs(root.right)
if lbst and rbst and lmax < root.data < rmin:
self.res = max(self.res, 1 + lcount + rcount)
return (
True,
min(lmin, root.data),
max(rmax, root.data),
1 + lcount + rcount,
)
else:
return False, root.data, root.data, 0
dfs(root)
return self.res | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FUNC_DEF IF VAR RETURN NUMBER BIN_OP NUMBER NUMBER BIN_OP NUMBER NUMBER NUMBER IF VAR VAR RETURN NUMBER VAR VAR NUMBER ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP BIN_OP NUMBER VAR VAR RETURN NUMBER FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP NUMBER VAR VAR RETURN NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
if root == None:
return 0
if self.isbst(root, -1000000, 100000000):
return self.size(root)
return max(self.largestBst(root.left), self.largestBst(root.right))
def size(self, root):
if root == None:
return 0
return 1 + self.size(root.left) + self.size(root.right)
def isbst(self, root, min, max):
if root == None:
return True
if root.data < min or root.data > max:
return False
return self.isbst(root.left, min, root.data - 1) and self.isbst(
root.right, root.data + 1, max
) | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NUMBER IF FUNC_CALL VAR VAR NUMBER NUMBER RETURN FUNC_CALL VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR NONE RETURN NUMBER RETURN BIN_OP BIN_OP NUMBER FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR NONE RETURN NUMBER IF VAR VAR VAR VAR RETURN NUMBER RETURN FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Node1:
def __init__(self, isBst, size, mini, maxi):
self.isBst = isBst
self.size = size
self.mini = mini
self.maxi = maxi
def bst(root):
if not root:
x = Node1(True, 0, 1000000, 0)
return x
left = bst(root.left)
right = bst(root.right)
if left.isBst and right.isBst and root.data > left.maxi and root.data < right.mini:
x = Node1(
True,
1 + left.size + right.size,
min(root.data, left.mini),
max(root.data, right.maxi),
)
else:
x = Node1(False, max(left.size, right.size), 1000000, 0)
return x
class Solution:
def largestBst(self, root):
return bst(root).size | CLASS_DEF FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR FUNC_DEF IF VAR ASSIGN VAR FUNC_CALL VAR NUMBER NUMBER NUMBER NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR VAR NUMBER NUMBER RETURN VAR CLASS_DEF FUNC_DEF RETURN FUNC_CALL VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class isBst:
def __init__(self, is_bst, total_node=1, min=float("-inf"), max=float("inf")):
self.bst = is_bst
self.length = total_node
self.min = min
self.max = max
def __str__(self):
return (
str(self.bst)
+ ", "
+ str(self.length)
+ ", "
+ str(self.min)
+ ", "
+ str(self.max)
)
class Solution:
def largestBst(self, root):
no_of_node = [0]
def rec(node):
if node.left is None and node.right is None:
return isBst(True, 1, node.data, node.data)
left = (
rec(node.left)
if node.left
else isBst(True, 0, node.data, node.data - 1)
)
right = (
rec(node.right)
if node.right
else isBst(True, 0, node.data + 1, node.data)
)
if left.bst and right.bst:
if left.max < node.data < right.min:
return isBst(
True, left.length + right.length + 1, left.min, right.max
)
return isBst(False, max(left.length, right.length))
return rec(root).length
def check_bst(self, root, no_of_node, low=float("-inf"), high=float("inf")):
if root is None:
return True
no_of_node[0] += 1
if not low < root.data < high:
return False
return self.check_bst(root.left, no_of_node, low, root.data) and self.check_bst(
root.right, no_of_node, root.data, high
) | CLASS_DEF FUNC_DEF NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR FUNC_DEF RETURN BIN_OP BIN_OP BIN_OP BIN_OP BIN_OP BIN_OP FUNC_CALL VAR VAR STRING FUNC_CALL VAR VAR STRING FUNC_CALL VAR VAR STRING FUNC_CALL VAR VAR CLASS_DEF FUNC_DEF ASSIGN VAR LIST NUMBER FUNC_DEF IF VAR NONE VAR NONE RETURN FUNC_CALL VAR NUMBER NUMBER VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR NUMBER NUMBER BIN_OP VAR NUMBER VAR IF VAR VAR IF VAR VAR VAR RETURN FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER VAR VAR RETURN FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR FUNC_DEF FUNC_CALL VAR STRING FUNC_CALL VAR STRING IF VAR NONE RETURN NUMBER VAR NUMBER NUMBER IF VAR VAR VAR RETURN NUMBER RETURN FUNC_CALL VAR VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
self.res = 0
def helper(root):
if not root:
return [float("inf"), float("-inf"), 0]
left = helper(root.left)
right = helper(root.right)
if root.data > left[1] and root.data < right[0]:
height = 1 + left[2] + right[2]
self.res = max(self.res, height)
return [min(root.data, left[0]), max(root.data, right[1]), height]
return [float("-inf"), float("inf"), 0]
helper(root)
return self.res | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FUNC_DEF IF VAR RETURN LIST FUNC_CALL VAR STRING FUNC_CALL VAR STRING NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN LIST FUNC_CALL VAR VAR VAR NUMBER FUNC_CALL VAR VAR VAR NUMBER VAR RETURN LIST FUNC_CALL VAR STRING FUNC_CALL VAR STRING NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class TreeNode:
def __init__(self, maxi, mini, isbst, size):
self.maxi = maxi
self.mini = mini
self.isbst = isbst
self.size = size
class Solution:
def largestBst(self, root):
def solve(root):
if not root:
return TreeNode(~sys.maxsize, sys.maxsize, True, 0)
left = solve(root.left)
right = solve(root.right)
if (
left.isbst
and right.isbst
and root.data > left.maxi
and root.data < right.mini
):
curr_maxi = max(root.data, right.maxi)
curr_mini = min(left.mini, root.data)
curr_isbst = True
curr_size = left.size + right.size + 1
return TreeNode(curr_maxi, curr_mini, curr_isbst, curr_size)
return TreeNode(
~sys.maxsize, sys.maxsize, False, max(left.size, right.size)
)
return solve(root).size | CLASS_DEF FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR CLASS_DEF FUNC_DEF FUNC_DEF IF VAR RETURN FUNC_CALL VAR VAR VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN FUNC_CALL VAR VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR NUMBER FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
def solve(root):
if not root:
return True, float("-inf"), float("inf"), 0
lbst, lmax, lmin, lcnt = solve(root.left)
rbst, rmax, rmin, rcnt = solve(root.right)
if lbst and rbst and lmax < root.data < rmin:
return True, max(root.data, rmax), min(root.data, lmin), 1 + lcnt + rcnt
else:
return False, 0, 0, max(lcnt, rcnt)
return solve(root)[3] | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR RETURN NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING NUMBER ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR RETURN NUMBER FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP NUMBER VAR VAR RETURN NUMBER NUMBER NUMBER FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
def solve(root):
if not root:
return [0, -1000000000.0, 1000000000.0]
if not root.left and not root.right:
return [1, root.data, root.data]
l = solve(root.left)
r = solve(root.right)
if root.data > l[1] and root.data < r[2]:
return [l[0] + r[0] + 1, max(root.data, r[1]), min(root.data, l[2])]
else:
return [max(l[0], r[0]), 1000000000.0, -1000000000.0]
return solve(root)[0] | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR RETURN LIST NUMBER NUMBER NUMBER IF VAR VAR RETURN LIST NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR VAR NUMBER RETURN LIST BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER FUNC_CALL VAR VAR VAR NUMBER FUNC_CALL VAR VAR VAR NUMBER RETURN LIST FUNC_CALL VAR VAR NUMBER VAR NUMBER NUMBER NUMBER RETURN FUNC_CALL VAR VAR NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
self.res = 1
def dfs(root):
if not root:
return True, 2**31, -2 * 31, 0
left = dfs(root.left)
right = dfs(root.right)
if left[2] < root.data < right[1] and left[0] and right[0]:
self.res = max(self.res, 1 + left[3] + right[3])
return (
True,
min(left[1], root.data),
max(right[2], root.data),
1 + left[3] + right[3],
)
else:
return (
False,
min(left[1], root.data),
max(right[2], root.data),
1 + left[3] + right[3],
)
dfs(root)
return self.res | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FUNC_DEF IF VAR RETURN NUMBER BIN_OP NUMBER NUMBER BIN_OP NUMBER NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER VAR VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR NUMBER RETURN NUMBER FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL VAR VAR NUMBER VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR NUMBER RETURN NUMBER FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL VAR VAR NUMBER VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class NodeValue:
def __init__(self, maximum, minimum, size):
self.maxNode = maximum
self.minNode = minimum
self.size = size
class Solution:
def solve(self, root):
if not root:
return NodeValue(float("-inf"), float("inf"), 0)
if root.left == None and root.right == None:
return NodeValue(root.data, root.data, 1)
l = self.solve(root.left)
r = self.solve(root.right)
if l.maxNode < root.data < r.minNode:
return NodeValue(
max(r.maxNode, root.data),
min(l.minNode, root.data),
1 + l.size + r.size,
)
return NodeValue(float("inf"), float("-inf"), max(l.size, r.size))
def largestBst(self, root):
ans = self.solve(root)
return ans.size | CLASS_DEF FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR CLASS_DEF FUNC_DEF IF VAR RETURN FUNC_CALL VAR FUNC_CALL VAR STRING FUNC_CALL VAR STRING NUMBER IF VAR NONE VAR NONE RETURN FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP NUMBER VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR STRING FUNC_CALL VAR STRING FUNC_CALL VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
if not root:
return 0
self.largest_val = 1
self.dfs(root)
return self.largest_val
def dfs(self, root):
if not root:
return False, 0, -10001, 10001
if not root.left and not root.right:
return True, 1, root.data, root.data
l_is_bst, l_size, l_min, l_max = self.dfs(root.left)
r_is_bst, r_size, r_min, r_max = self.dfs(root.right)
if l_is_bst and r_is_bst and l_max < root.data < r_min:
curr_size = 1 + l_size + r_size
self.largest_val = max(self.largest_val, curr_size)
return True, curr_size, l_min, r_max
elif l_is_bst and l_max < root.data and not root.right:
curr_size = 1 + l_size
self.largest_val = max(self.largest_val, curr_size)
return True, curr_size, l_min, root.data
elif r_is_bst and root.data < r_min and not root.left:
curr_size = 1 + r_size
self.largest_val = max(self.largest_val, curr_size)
return True, curr_size, root.data, r_max
else:
return False, 0, -10001, 10001 | CLASS_DEF FUNC_DEF IF VAR RETURN NUMBER ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF IF VAR RETURN NUMBER NUMBER NUMBER NUMBER IF VAR VAR RETURN NUMBER NUMBER VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN NUMBER VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR BIN_OP NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN NUMBER VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR BIN_OP NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN NUMBER VAR VAR VAR RETURN NUMBER NUMBER NUMBER NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def countnodes(self, root):
if root == None:
return 0
ln = self.countnodes(root.left)
rn = self.countnodes(root.right)
return 1 + ln + rn
def isbst(self, root, mini, maxi):
if root == None:
return True
if mini < root.data and root.data < maxi:
return self.isbst(root.left, mini, root.data) and self.isbst(
root.right, root.data, maxi
)
else:
return False
def f(self, root, a):
if root == None:
return 0
mini = -sys.maxsize
maxi = sys.maxsize
if self.isbst(root, mini, maxi):
a[0] = max(a[0], self.countnodes(root))
self.f(root.left, a)
self.f(root.right, a)
return a[0]
def largestBst(self, root):
a = [1]
return self.f(root, a) | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN BIN_OP BIN_OP NUMBER VAR VAR FUNC_DEF IF VAR NONE RETURN NUMBER IF VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR RETURN NUMBER FUNC_DEF IF VAR NONE RETURN NUMBER ASSIGN VAR VAR ASSIGN VAR VAR IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR RETURN VAR NUMBER FUNC_DEF ASSIGN VAR LIST NUMBER RETURN FUNC_CALL VAR VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
def large(root):
if root is None:
return [float("inf"), float("-inf"), 0]
if root.left is None and root.right is None:
return [root.data, root.data, 1]
left = large(root.left)
right = large(root.right)
ans = [0, 0, 0]
if root.data > left[1] and root.data < right[0]:
ans[0] = min(left[0], right[0], root.data)
ans[1] = max(left[1], right[1], root.data)
ans[2] = left[2] + right[2] + 1
return ans
ans = [float("-inf"), float("inf"), max(left[2], right[2])]
return ans
return large(root)[2] | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR NONE RETURN LIST FUNC_CALL VAR STRING FUNC_CALL VAR STRING NUMBER IF VAR NONE VAR NONE RETURN LIST VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER IF VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR NUMBER VAR ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR NUMBER VAR ASSIGN VAR NUMBER BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER RETURN VAR ASSIGN VAR LIST FUNC_CALL VAR STRING FUNC_CALL VAR STRING FUNC_CALL VAR VAR NUMBER VAR NUMBER RETURN VAR RETURN FUNC_CALL VAR VAR NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
ans = [0]
def solve(root):
if root == None:
return [999999, -999999, 0, True]
left = solve(root.left)
right = solve(root.right)
left_min = min(root.data, left[0], right[0])
right_max = max(root.data, left[1], right[1])
size = left[2] + right[2] + 1
if root.data <= left[1] or root.data >= right[0]:
return [left_min, right_max, size, False]
if left[3] and right[3]:
ans[0] = max(size, ans[0])
return [left_min, right_max, size, True]
return [left_min, right_max, size, False]
solve(root)
return ans[0] | CLASS_DEF FUNC_DEF ASSIGN VAR LIST NUMBER FUNC_DEF IF VAR NONE RETURN LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER IF VAR VAR NUMBER VAR VAR NUMBER RETURN LIST VAR VAR VAR NUMBER IF VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER FUNC_CALL VAR VAR VAR NUMBER RETURN LIST VAR VAR VAR NUMBER RETURN LIST VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | from sys import maxsize
class Answer:
def __init__(self, maxi=-maxsize, mini=maxsize, is_bst=True, size=0):
self.maxi = maxi
self.mini = mini
self.is_bst = is_bst
self.size = size
class Solution:
def solve(self, root):
if root is None:
return Answer()
left = self.solve(root.left)
right = self.solve(root.right)
curr = Answer()
curr.maxi = max(root.data, right.maxi)
curr.mini = min(root.data, left.mini)
if left.is_bst and right.is_bst and left.maxi < root.data < right.mini:
curr.is_bst = True
curr.size = left.size + right.size + 1
else:
curr.is_bst = False
curr.size = max(left.size, right.size)
return curr
def largestBst(self, root):
ans = self.solve(root)
return ans.size | CLASS_DEF FUNC_DEF VAR VAR NUMBER NUMBER ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR CLASS_DEF FUNC_DEF IF VAR NONE RETURN FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class BstNode:
def __init__(self, size=0, smallest=float("inf"), largest=float("-inf")):
self.smallest = smallest
self.largest = largest
self.size = size
class Solution:
def solve(self, root):
if root is None:
return BstNode()
leftBst = self.solve(root.left)
rightBst = self.solve(root.right)
if leftBst.largest < root.data and rightBst.smallest > root.data:
if root.left is not None:
currSmallest = leftBst.smallest
else:
currSmallest = root.data
if root.right is not None:
currLargest = rightBst.largest
else:
currLargest = root.data
currSize = leftBst.size + rightBst.size + 1
else:
currSmallest = float("-inf")
currLargest = float("inf")
currSize = max(leftBst.size, rightBst.size)
return BstNode(currSize, currSmallest, currLargest)
def largestBst(self, root):
bstNode = self.solve(root)
return bstNode.size | CLASS_DEF FUNC_DEF NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR CLASS_DEF FUNC_DEF IF VAR NONE RETURN FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR IF VAR NONE ASSIGN VAR VAR ASSIGN VAR VAR IF VAR NONE ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
global c
def b(self, r):
global c
if not r:
return [0, float("+inf"), float("-inf"), True]
if not r.left and not r.right:
return [1, r.data, r.data, True]
l = self.b(r.left)
ri = self.b(r.right)
if l[3] and ri[3] and l[2] < r.data and r.data < ri[1]:
c = max(c, l[0] + ri[0] + 1)
return [l[0] + ri[0] + 1, min(l[1], r.data), max(ri[2], r.data), True]
return [max(l[0], ri[0]), float("-inf"), float("+inf"), False]
def largestBst(self, root):
global c
c = 0
self.b(root)
if c == 0:
return 1
return c | CLASS_DEF FUNC_DEF IF VAR RETURN LIST NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING NUMBER IF VAR VAR RETURN LIST NUMBER VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER VAR NUMBER VAR NUMBER VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER RETURN LIST BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER RETURN LIST FUNC_CALL VAR VAR NUMBER VAR NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING NUMBER FUNC_DEF ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR IF VAR NUMBER RETURN NUMBER RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
no_of_node = [0]
def traverse(node):
if node is None:
return 0
node_count = [0]
if self.check_bst(node, node_count):
return node_count[0]
return max(traverse(node.right), traverse(node.left))
return traverse(root)
def check_bst(self, root, no_of_node, low=float("-inf"), high=float("inf")):
if root is None:
return True
no_of_node[0] += 1
if not low < root.data < high:
return False
return self.check_bst(root.left, no_of_node, low, root.data) and self.check_bst(
root.right, no_of_node, root.data, high
) | CLASS_DEF FUNC_DEF ASSIGN VAR LIST NUMBER FUNC_DEF IF VAR NONE RETURN NUMBER ASSIGN VAR LIST NUMBER IF FUNC_CALL VAR VAR VAR RETURN VAR NUMBER RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR VAR FUNC_DEF FUNC_CALL VAR STRING FUNC_CALL VAR STRING IF VAR NONE RETURN NUMBER VAR NUMBER NUMBER IF VAR VAR VAR RETURN NUMBER RETURN FUNC_CALL VAR VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class node:
def __init__(self, mini, maxi, size):
self.maxi = maxi
self.mini = mini
self.size = size
class Solution:
def f(self, root):
if root == None:
return node(sys.maxsize, -sys.maxsize, 0)
lt = self.f(root.left)
rt = self.f(root.right)
if lt.maxi < root.data and root.data < rt.mini:
return node(
min(root.data, lt.mini), max(root.data, rt.maxi), lt.size + rt.size + 1
)
return node(-sys.maxsize, sys.maxsize, max(lt.size, rt.size))
def largestBst(self, root):
a = self.f(root)
return a.size | CLASS_DEF FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR CLASS_DEF FUNC_DEF IF VAR NONE RETURN FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def tt(self, root):
if root == None:
return True, 1000001, -1, 0
if root.left == None and root.right == None:
return True, root.data, root.data, 1
islbst, lmin, lmax, nl = self.tt(root.left)
isrbst, rmin, rmax, nr = self.tt(root.right)
mini = min(lmin, rmin, root.data)
maxi = max(lmax, rmax, root.data)
if islbst == False or isrbst == False:
return False, mini, maxi, max(nr, nl)
if root.data <= lmax or root.data >= rmin:
nmaxi = max(nr, nl)
return False, mini, maxi, nmaxi
return True, mini, maxi, nl + nr + 1
def largestBst(self, root):
isbst, mini, maxi, n = self.tt(root)
return n | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NUMBER NUMBER NUMBER NUMBER IF VAR NONE VAR NONE RETURN NUMBER VAR VAR NUMBER ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR IF VAR NUMBER VAR NUMBER RETURN NUMBER VAR VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN NUMBER VAR VAR VAR RETURN NUMBER VAR VAR BIN_OP BIN_OP VAR VAR NUMBER FUNC_DEF ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR RETURN VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
if root == None:
return 0
if self.isbst(root, -9999, 99999):
return self.size(root)
return max(self.largestBst(root.left), self.largestBst(root.right))
def isbst(self, root, mini, maxi):
if root == None:
return True
if root.data <= mini or root.data >= maxi:
return False
return self.isbst(root.left, mini, root.data) and self.isbst(
root.right, root.data, maxi
)
def size(self, root):
if root == None:
return 0
return self.size(root.left) + self.size(root.right) + 1 | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NUMBER IF FUNC_CALL VAR VAR NUMBER NUMBER RETURN FUNC_CALL VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR NONE RETURN NUMBER IF VAR VAR VAR VAR RETURN NUMBER RETURN FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR FUNC_DEF IF VAR NONE RETURN NUMBER RETURN BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
def rec(root):
if root is None:
return [True, 2**31, -2 * 31, 0]
if root.left is None and root.right is None:
return [True, root.data, root.data, 1]
l = rec(root.left)
r = rec(root.right)
if l[0] and r[0] and l[2] < root.data and r[1] > root.data:
return [
True,
min(l[1], root.data),
max(root.data, r[2]),
l[3] + r[3] + 1,
]
else:
return [
False,
min(l[1], root.data),
max(root.data, r[2]),
max(l[3], r[3]),
]
return rec(root)[3] | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR NONE RETURN LIST NUMBER BIN_OP NUMBER NUMBER BIN_OP NUMBER NUMBER NUMBER IF VAR NONE VAR NONE RETURN LIST NUMBER VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER VAR NUMBER VAR NUMBER VAR VAR NUMBER VAR RETURN LIST NUMBER FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL VAR VAR VAR NUMBER BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER RETURN LIST NUMBER FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL VAR VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR NUMBER RETURN FUNC_CALL VAR VAR NUMBER |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
if not root:
return 0
elif self.checkIfBST(root, -float("inf"), float("inf")):
return self.getSizeOfTree(root)
else:
return max(self.largestBst(root.left), self.largestBst(root.right))
def getSizeOfTree(self, root):
if not root:
return 0
else:
return 1 + self.getSizeOfTree(root.left) + self.getSizeOfTree(root.right)
def checkIfBST(self, root, lbound, rbound):
if not root:
return True
else:
return (
lbound < root.data < rbound
and self.checkIfBST(root.left, lbound, root.data)
and self.checkIfBST(root.right, root.data, rbound)
) | CLASS_DEF FUNC_DEF IF VAR RETURN NUMBER IF FUNC_CALL VAR VAR FUNC_CALL VAR STRING FUNC_CALL VAR STRING RETURN FUNC_CALL VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR RETURN NUMBER RETURN BIN_OP BIN_OP NUMBER FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR RETURN NUMBER RETURN VAR VAR VAR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR |
Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 10^{5}
1 ≤ Data of a node ≤ 10^{6} | class Solution:
def largestBst(self, root):
def recurDown(root: Node):
if not root:
return [0, 1000000000, -1000000000]
if (not root.left) & (not root.right):
return [1, root.data, root.data]
rightData = recurDown(root.right)
leftData = recurDown(root.left)
if rightData[1] > root.data and leftData[2] < root.data:
if rightData[0] <= 0:
return [rightData[0] + leftData[0] + 1, leftData[1], root.data]
if leftData[0] <= 0:
return [rightData[0] + leftData[0] + 1, root.data, rightData[2]]
return [rightData[0] + leftData[0] + 1, leftData[1], rightData[2]]
else:
return [max(rightData[0], leftData[0]), -1000000000, 1000000000]
return recurDown(root)[0] | CLASS_DEF FUNC_DEF FUNC_DEF VAR IF VAR RETURN LIST NUMBER NUMBER NUMBER IF BIN_OP VAR VAR RETURN LIST NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER VAR VAR NUMBER VAR IF VAR NUMBER NUMBER RETURN LIST BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER VAR NUMBER VAR IF VAR NUMBER NUMBER RETURN LIST BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER VAR VAR NUMBER RETURN LIST BIN_OP BIN_OP VAR NUMBER VAR NUMBER NUMBER VAR NUMBER VAR NUMBER RETURN LIST FUNC_CALL VAR VAR NUMBER VAR NUMBER NUMBER NUMBER RETURN FUNC_CALL VAR VAR NUMBER |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.x_idxs = x_idxs = defaultdict(list)
for i, x in enumerate(arr):
x_idxs[x].append(i)
self.xs = sorted(list(x_idxs.keys()), key=lambda x: -len(x_idxs[x]))
def query(self, left: int, right: int, threshold: int) -> int:
for x in self.xs:
idxs = self.x_idxs[x]
if len(idxs) < threshold:
break
r = bisect.bisect_right(idxs, right)
l = bisect.bisect_right(idxs, left - 1)
if r - l >= threshold:
return x
return -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_DEF VAR VAR VAR FOR VAR VAR ASSIGN VAR VAR VAR IF FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.loc = collections.defaultdict(list)
for i, n in enumerate(arr):
self.loc[n].append(i)
self.nums = sorted(
list(self.loc.keys()), key=lambda n: len(self.loc[n]), reverse=True
)
print(self.nums)
def query(self, left: int, right: int, threshold: int) -> int:
for n in self.nums:
if len(self.loc[n]) < threshold:
return -1
l, r = bisect.bisect_left(self.loc[n], left), bisect.bisect_right(
self.loc[n], right
)
if r - l >= threshold:
return n
return -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR FUNC_DEF VAR VAR VAR FOR VAR VAR IF FUNC_CALL VAR VAR VAR VAR RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, nums):
atoi = defaultdict(list)
for i, num in enumerate(nums):
atoi[num].append(i)
self.nums = nums
self.atoi = atoi
def query(self, left, right, threshold):
for _ in range(20):
rand = self.nums[random.randint(left, right)]
left_element = bisect.bisect_left(self.atoi[rand], left)
right_element = bisect.bisect(self.atoi[rand], right)
if right_element - left_element >= threshold:
return rand
return -1 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR FUNC_DEF FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.num_to_index = collections.defaultdict(list)
for x in range(len(arr)):
self.num_to_index[arr[x]].append(x)
self.arr = arr
def query(self, left: int, right: int, threshold: int) -> int:
visited = set()
length = right - left + 1
for x in range(left, right + 1):
if self.arr[x] in visited:
continue
left_i = bisect.bisect_left(self.num_to_index[self.arr[x]], left)
right_i = bisect.bisect_right(self.num_to_index[self.arr[x]], right) - 1
if right_i - left_i + 1 >= threshold:
return self.arr[x]
length = length - (right_i - left_i + 1)
if threshold > length:
return -1
visited.add(self.arr[x])
return -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR FUNC_DEF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER IF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR VAR VAR NUMBER IF BIN_OP BIN_OP VAR VAR NUMBER VAR RETURN VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR RETURN NUMBER EXPR FUNC_CALL VAR VAR VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.tables = collections.defaultdict(list)
for i, num in enumerate(arr):
self.tables[num].append(i)
def query(self, left: int, right: int, threshold: int) -> int:
if right - left + 1 < threshold:
return -1
for num in self.tables:
if len(self.tables[num]) < threshold:
continue
l = self.leftSearch(self.tables[num], left)
r = self.rightSearch(self.tables[num], right)
if r - l >= threshold:
return num
return -1
def leftSearch(self, array, target):
l = 0
r = len(array)
while l < r:
m = (l + r) // 2
if array[m] < target:
l = m + 1
else:
r = m
return l
def rightSearch(self, array, target):
l = 0
r = len(array)
while l < r:
m = (l + r) // 2
if array[m] <= target:
l = m + 1
else:
r = m
return l | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF VAR VAR VAR IF BIN_OP BIN_OP VAR VAR NUMBER VAR RETURN NUMBER FOR VAR VAR IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR RETURN VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.N = len(arr)
self.max_len = 1 << ceil(log2(self.N)) + 1
self.seg = [None] * self.max_len
self.build(1, 0, self.N - 1, arr)
self.indices = defaultdict(list)
for i, a in enumerate(arr):
self.indices[a].append(i)
def query(self, left: int, right: int, threshold: int) -> int:
def bs(arr, l, r, target):
while l <= r:
m = l + (r - l) // 2
if arr[m] <= target:
l = m + 1
else:
r = m - 1
return r
major = self.seg_query(1, 0, self.N - 1, left, right)[0]
lst = self.indices[major]
l, r = bs(lst, 0, len(lst) - 1, left - 1), bs(lst, 0, len(lst) - 1, right)
if r - l >= threshold:
return major
return -1
def build(self, idx, s, e, arr):
if s == e:
self.seg[idx] = [arr[s], 1]
return
m = s + (e - s) // 2
self.build(2 * idx, s, m, arr)
self.build(2 * idx + 1, m + 1, e, arr)
self.seg[idx] = self.merge(self.seg[2 * idx], self.seg[2 * idx + 1])
def seg_query(self, idx, s, e, l, r):
if s >= l and e <= r:
return self.seg[idx]
if s > r or e < l:
return [0, 0]
m = s + (e - s) // 2
return self.merge(
self.seg_query(2 * idx, s, m, l, r),
self.seg_query(2 * idx + 1, m + 1, e, l, r),
)
def merge(self, A, B):
lv, lf = A
rv, rf = B
if lv == rv:
return [lv, lf + rf]
elif lf > rf:
return [lv, lf - rf]
else:
return [rv, rf - lf] | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER BIN_OP FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NONE VAR EXPR FUNC_CALL VAR NUMBER NUMBER BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF VAR VAR VAR FUNC_DEF WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR NUMBER NUMBER BIN_OP VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER BIN_OP VAR NUMBER FUNC_CALL VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER VAR IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER VAR FUNC_DEF IF VAR VAR ASSIGN VAR VAR LIST VAR VAR NUMBER RETURN ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP NUMBER VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP VAR NUMBER VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR BIN_OP NUMBER VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF IF VAR VAR VAR VAR RETURN VAR VAR IF VAR VAR VAR VAR RETURN LIST NUMBER NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN FUNC_CALL VAR FUNC_CALL VAR BIN_OP NUMBER VAR VAR VAR VAR VAR FUNC_CALL VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP VAR NUMBER VAR VAR VAR FUNC_DEF ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR IF VAR VAR RETURN LIST VAR BIN_OP VAR VAR IF VAR VAR RETURN LIST VAR BIN_OP VAR VAR RETURN LIST VAR BIN_OP VAR VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.idxes = collections.defaultdict(list)
for i, n in enumerate(arr):
self.idxes[n].append(i)
self.arr = arr
self.st = SegmentTree(len(arr), arr, self.idxes)
def query(self, left: int, right: int, threshold: int) -> int:
maj = self.st.query_maj(left, right)
if maj:
l, r = bisect.bisect_left(self.idxes[maj], left), bisect.bisect(
self.idxes[maj], right
)
if r - l >= threshold:
return maj
return -1
class SegmentTree:
def __init__(self, n, arr, idxes):
self.root = Node(0, n - 1, arr, idxes)
def query_maj(self, lo, hi):
return self.root.query_maj(lo, hi)
class Node:
def __init__(self, lo, hi, arr, idxes):
self.lo, self.hi = lo, hi
self.lc, self.rc = None, None
self.arr, self.idxes = arr, idxes
self.maj = None
def query_maj(self, lo, hi):
def is_maj(n):
if not n:
return False
l = bisect.bisect_left(self.idxes[n], lo)
r = bisect.bisect(self.idxes[n], hi)
return r - l << 1 > hi - lo
if lo > hi or self.lo > hi or self.hi < lo:
return None
if lo <= self.lo <= self.hi <= hi:
if not self.maj:
if self.lo == self.hi:
self.maj = self.arr[self.lo]
else:
l, r = None, None
mi = self.lo + self.hi >> 1
if not self.lc:
self.lc = Node(self.lo, mi, self.arr, self.idxes)
l = self.lc.query_maj(self.lo, mi)
if not self.rc:
self.rc = Node(mi + 1, self.hi, self.arr, self.idxes)
r = self.rc.query_maj(mi + 1, self.hi)
self.maj = l if is_maj(l) else r if is_maj(r) else -1
return self.maj
mi = self.lo + self.hi >> 1
l, r = None, None
if lo <= mi:
if not self.lc:
self.lc = Node(self.lo, mi, self.arr, self.idxes)
l = self.lc.query_maj(max(self.lo, lo), min(mi, hi))
if mi + 1 <= hi:
if not self.rc:
self.rc = Node(mi + 1, self.hi, self.arr, self.idxes)
r = self.rc.query_maj(max(lo, mi + 1), min(self.hi, hi))
return l if is_maj(l) else r if is_maj(r) else -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR FUNC_DEF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER VAR CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR VAR FUNC_DEF RETURN FUNC_CALL VAR VAR VAR CLASS_DEF FUNC_DEF ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR NONE NONE ASSIGN VAR VAR VAR VAR ASSIGN VAR NONE FUNC_DEF FUNC_DEF IF VAR RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR RETURN BIN_OP BIN_OP VAR VAR NUMBER BIN_OP VAR VAR IF VAR VAR VAR VAR VAR VAR RETURN NONE IF VAR VAR VAR VAR IF VAR IF VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR NONE NONE ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR NUMBER RETURN VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR VAR NONE NONE IF VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR IF BIN_OP VAR NUMBER VAR IF VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR NUMBER |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.indices = defaultdict(list)
for a in set(arr):
self.indices[a].append(-1)
for i, a in enumerate(arr):
self.indices[a].append(i)
self.a = list(self.indices.keys())
def query(self, left: int, right: int, threshold: int) -> int:
def bs(arr, l, r, target):
while l <= r:
m = l + (r - l) // 2
if arr[m] <= target:
l = m + 1
else:
r = m - 1
return r
for _ in range(20):
a = random.choice(self.a)
lst = self.indices[a]
l, r = bs(lst, 0, len(lst) - 1, left - 1), bs(lst, 0, len(lst) - 1, right)
if r - l >= threshold:
return a
return -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR NUMBER FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_DEF VAR VAR VAR FUNC_DEF WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER BIN_OP VAR NUMBER FUNC_CALL VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER VAR IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.arr = arr
self.data = defaultdict(list)
for i, num in enumerate(arr):
self.data[num] += [i]
def query(self, left: int, right: int, threshold: int) -> int:
counter = defaultdict(int)
for _ in range(32):
index = random.randint(left, right)
counter[self.arr[index]] += 1
max_cnts = sorted(
[(value, key) for key, value in list(counter.items())], reverse=True
)[:2]
for value, key in max_cnts:
i = bisect.bisect_left(self.data[key], left)
j = bisect.bisect_right(self.data[key], right)
if j - i >= threshold:
return key
return -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR VAR VAR LIST VAR FUNC_DEF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR NUMBER NUMBER FOR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.x_idxs = x_idxs = defaultdict(list)
for i, x in enumerate(arr):
x_idxs[x].append(i)
self.a = arr
self.n = n = len(arr)
self.tree = [-1] * (n * 4)
self.build_tree(1, 0, n - 1)
def build_tree(self, v, l, r):
a, tree = self.a, self.tree
if l == r:
tree[v] = a[l]
return
mid = (l + r) // 2
self.build_tree(2 * v, l, mid)
self.build_tree(2 * v + 1, mid + 1, r)
if tree[2 * v] != -1 and self.count(tree[2 * v], l, r) * 2 > r - l + 1:
tree[v] = tree[2 * v]
elif (
tree[2 * v + 1] != -1 and self.count(tree[2 * v + 1], l, r) * 2 > r - l + 1
):
tree[v] = tree[2 * v + 1]
def count(self, x, l, r):
f = bisect.bisect_right
idxs = self.x_idxs[x]
return f(idxs, r) - f(idxs, l - 1)
def query_tree(self, v, l, r, queryl, queryr):
tree = self.tree
if queryr < l or r < queryl:
return -1, -1
if queryl <= l and r <= queryr:
if tree[v] == -1:
return -1, -1
x = tree[v]
xcount = self.count(x, queryl, queryr)
return (x, xcount) if xcount * 2 > queryr - queryl + 1 else (-1, -1)
mid = (l + r) // 2
res_left = self.query_tree(2 * v, l, mid, queryl, queryr)
if res_left[0] > -1:
return res_left
res_right = self.query_tree(2 * v + 1, mid + 1, r, queryl, queryr)
if res_right[0] > -1:
return res_right
return -1, -1
def query(self, left, right, threshold):
res = self.query_tree(1, 0, self.n - 1, left, right)
if res[1] >= threshold:
return res[0]
return -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR RETURN ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP NUMBER VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP VAR NUMBER VAR IF VAR BIN_OP NUMBER VAR NUMBER BIN_OP FUNC_CALL VAR VAR BIN_OP NUMBER VAR VAR VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR VAR VAR BIN_OP NUMBER VAR IF VAR BIN_OP BIN_OP NUMBER VAR NUMBER NUMBER BIN_OP FUNC_CALL VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR VAR RETURN BIN_OP FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR VAR IF VAR VAR VAR VAR RETURN NUMBER NUMBER IF VAR VAR VAR VAR IF VAR VAR NUMBER RETURN NUMBER NUMBER ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR RETURN BIN_OP VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP NUMBER VAR VAR VAR VAR VAR IF VAR NUMBER NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP VAR NUMBER VAR VAR VAR IF VAR NUMBER NUMBER RETURN VAR RETURN NUMBER NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR NUMBER NUMBER BIN_OP VAR NUMBER VAR VAR IF VAR NUMBER VAR RETURN VAR NUMBER RETURN NUMBER |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, A):
a2i = collections.defaultdict(list)
for i, x in enumerate(A):
a2i[x].append(i)
self.a, self.a2i = A, a2i
def query(self, left: int, right: int, threshold: int) -> int:
track = self.a2i
l, r = left, right
if (r - l + 1) % 2 == 0:
mid = l - 1 + (r - l + 1) // 2
else:
mid = l + (r - l + 1) // 2
if (r - mid + 1) % 2 == 0:
mid1 = mid - 1 + (r - mid + 1) // 2
else:
mid1 = mid + (r - mid + 1) // 2
if (mid - l + 1) % 2 == 0:
mid2 = l - 1 + (mid - l + 1) // 2
else:
mid2 = l + (mid - l + 1) // 2
t1 = bisect.bisect_left(track[self.a[mid]], left)
t2 = bisect.bisect_right(track[self.a[mid]], right)
if t2 - t1 >= threshold:
return self.a[mid]
t1 = bisect.bisect_left(track[self.a[mid1]], left)
t2 = bisect.bisect_right(track[self.a[mid1]], right)
if t2 - t1 >= threshold:
return self.a[mid1]
t1 = bisect.bisect_left(track[self.a[mid2]], left)
t2 = bisect.bisect_right(track[self.a[mid2]], right)
if t2 - t1 >= threshold:
return self.a[mid2]
return -1 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR FUNC_DEF VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR IF BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER IF BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER IF BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.n = len(arr)
self.counts = [Counter() for _ in range(self.n * 2)]
for i, num in enumerate(arr):
self.counts[i + self.n][num] += 1
for i in range(self.n)[::-1]:
self.counts[i] = self.counts[i * 2] + self.counts[i * 2 + 1]
def query(self, left: int, right: int, threshold: int) -> int:
left += self.n
right += self.n + 1
c = Counter()
while left < right:
if left % 2 == 1:
c += self.counts[left]
left += 1
if right % 2 == 1:
right -= 1
c += self.counts[right]
right //= 2
left //= 2
topcount, topnum = max((ct, num) for num, ct in list(c.items()))
return topnum if topcount >= threshold else -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER FOR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR BIN_OP VAR BIN_OP VAR NUMBER VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF VAR VAR VAR VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR WHILE VAR VAR IF BIN_OP VAR NUMBER NUMBER VAR VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR NUMBER VAR VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR RETURN VAR VAR VAR NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class Node:
def __init__(self, left, right):
self.i = left
self.j = right
self.left = None
self.right = None
self.Maj = None
self.Maj_f = 0
class MajorityChecker:
def __init__(self, arr: List[int]):
def DFS(i, j):
node = Node(i, j)
if i == j:
node.Maj = arr[i]
node.Maj_f = 1
else:
m = (i + j) // 2
node.left, a, b = DFS(i, m)
node.right, c, d = DFS(m + 1, j)
if a == c:
node.Maj = a
node.Maj_f = b + d
elif b > d:
node.Maj = a
node.Maj_f = b - d
else:
node.Maj = c
node.Maj_f = d - b
return node, node.Maj, node.Maj_f
self.root = DFS(0, len(arr) - 1)[0]
self.index = defaultdict(list)
for i, num in enumerate(arr):
self.index[num].append(i)
def DFS(self, node, l, r):
if node.i == l and node.j == r:
return node.Maj, node.Maj_f
m = (node.i + node.j) // 2
if l > m:
return self.DFS(node.right, l, r)
elif r < m + 1:
return self.DFS(node.left, l, r)
else:
a, b = self.DFS(node.left, l, m)
c, d = self.DFS(node.right, m + 1, r)
if a == c:
return a, b + d
elif b > d:
return a, b - d
else:
return c, d - b
def query(self, left: int, right: int, threshold: int) -> int:
candidate = self.DFS(self.root, left, right)[0]
if threshold <= bisect.bisect_right(
self.index[candidate], right
) - bisect.bisect_left(self.index[candidate], left):
return candidate
else:
return -1 | CLASS_DEF FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR NONE ASSIGN VAR NONE ASSIGN VAR NONE ASSIGN VAR NUMBER CLASS_DEF FUNC_DEF VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR VAR RETURN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF IF VAR VAR VAR VAR RETURN VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR RETURN FUNC_CALL VAR VAR VAR VAR IF VAR BIN_OP VAR NUMBER RETURN FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR IF VAR VAR RETURN VAR BIN_OP VAR VAR IF VAR VAR RETURN VAR BIN_OP VAR VAR RETURN VAR BIN_OP VAR VAR FUNC_DEF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR BIN_OP FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR RETURN VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.idx = collections.defaultdict(list)
for i, a in enumerate(arr):
self.idx[a].append(i)
print(self.idx)
def query(self, left: int, right: int, threshold: int) -> int:
for k, v in list(self.idx.items()):
l = bisect.bisect_left(v, left)
r = bisect.bisect_right(v, right)
if r - l >= threshold:
return k
return -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF VAR VAR VAR FOR VAR VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF BIN_OP VAR VAR VAR RETURN VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.arr = arr
self.prearr = [[] for _ in range(max(arr) + 1)]
for i in range(len(arr)):
self.prearr[arr[i]].append(i)
def query(self, left: int, right: int, threshold: int) -> int:
def checkmajority(k):
lo = 0
hi = len(self.prearr[k]) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if self.prearr[k][mid] >= left:
hi = mid
else:
lo = mid + 1
start = lo
lo = 0
hi = len(self.prearr[k]) - 1
while lo < hi:
mid = lo + (hi - lo + 1) // 2
if self.prearr[k][mid] <= right:
lo = mid
else:
hi = mid - 1
end = lo
if end - start + 1 >= threshold:
return True
else:
return False
res = False
a = self.arr[left : right + 1]
for _ in range(10):
k = random.choice(a)
res = res or checkmajority(k)
if res:
return k
return -1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR ASSIGN VAR LIST VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR FUNC_DEF VAR VAR VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR IF BIN_OP BIN_OP VAR VAR NUMBER VAR RETURN NUMBER RETURN NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR IF VAR RETURN VAR RETURN NUMBER VAR |
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000 | class MajorityChecker:
def __init__(self, arr: List[int]):
self.arr = arr
self.numDict = defaultdict(list)
for i, num in enumerate(arr):
self.numDict[num].append(i)
def query(self, left: int, right: int, threshold: int) -> int:
leftCandi = right - left + 1
iNow = right
visited = set()
while leftCandi >= threshold:
if self.arr[iNow] not in visited:
visited.add(self.arr[iNow])
numOfINow = self.count(iNow, left)
if numOfINow >= threshold:
return self.arr[iNow]
else:
leftCandi -= numOfINow
iNow -= 1
return -1
def count(self, i0, left):
num = self.arr[i0]
listLen = len(self.numDict[num])
l = 0
r = listLen - 1
if i0 == self.numDict[num][r]:
right = r
elif i0 == self.numDict[num][l]:
right = l
else:
while r > l:
m = (r + l) // 2
if self.numDict[num][m] < i0:
l = m + 1
elif self.numDict[num][m] > i0:
r = m
else:
l = m
r = l - 1
right = l
l = 0
r = right
if left <= self.numDict[num][l]:
return right + 1
while r > l:
m = (r + l) // 2
if self.numDict[num][m] < left:
l = m + 1
else:
r = m
return right - l + 1 | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR WHILE VAR VAR IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR RETURN VAR VAR VAR VAR VAR NUMBER RETURN NUMBER VAR FUNC_DEF ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR ASSIGN VAR NUMBER ASSIGN VAR VAR IF VAR VAR VAR VAR RETURN BIN_OP VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR RETURN BIN_OP BIN_OP VAR VAR NUMBER |
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Try to solve it in linear time/space. | class Solution:
def maximumGap(self, nums):
if len(nums) < 2:
return 0
a = nums[0]
b = nums[0]
for num in nums:
a = min(a, num)
b = max(b, num)
bucketSize = max(1, (b - a) // (len(nums) - 1))
bucketNum = (b - a) // bucketSize + 1
buckets = [[-1, -1] for i in range(bucketNum)]
for num in nums:
locate = (num - a) // bucketSize
if buckets[locate][0] == -1:
buckets[locate][0] = num
buckets[locate][1] = num
else:
buckets[locate][0] = min(num, buckets[locate][0])
buckets[locate][1] = max(num, buckets[locate][1])
maxGap = 0
pre = a
for bucket in buckets:
if bucket[0] == -1:
continue
maxGap = max(maxGap, bucket[0] - pre)
pre = bucket[1]
return maxGap | CLASS_DEF FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR LIST NUMBER NUMBER VAR FUNC_CALL VAR VAR FOR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR IF VAR VAR NUMBER NUMBER ASSIGN VAR VAR NUMBER VAR ASSIGN VAR VAR NUMBER VAR ASSIGN VAR VAR NUMBER FUNC_CALL VAR VAR VAR VAR NUMBER ASSIGN VAR VAR NUMBER FUNC_CALL VAR VAR VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR FOR VAR VAR IF VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR NUMBER RETURN VAR |
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Try to solve it in linear time/space. | class Solution:
def maximumGap(self, nums):
if len(nums) < 2:
return 0
m = 0
for num in nums:
m = max(m, num)
exp = 1
while m // exp:
aux = [[] for i in range(10)]
for num in nums:
aux[num // exp % 10].append(num)
index = 0
for item in aux:
if len(item) != 0:
for i in item:
nums[index] = i
index += 1
exp *= 10
maxGap = 0
pre = nums[0]
for num in nums:
maxGap = max(maxGap, num - pre)
pre = num
return maxGap | CLASS_DEF FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR ASSIGN VAR LIST VAR FUNC_CALL VAR NUMBER FOR VAR VAR EXPR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER VAR ASSIGN VAR NUMBER FOR VAR VAR IF FUNC_CALL VAR VAR NUMBER FOR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR RETURN VAR |
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Try to solve it in linear time/space. | class Solution:
def maximumGap(self, nums):
nums.sort()
try:
return max(list(map(lambda i, j: j - i, nums, nums[1:])))
except:
return 0 | CLASS_DEF FUNC_DEF EXPR FUNC_CALL VAR RETURN FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR BIN_OP VAR VAR VAR VAR NUMBER RETURN NUMBER |
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Try to solve it in linear time/space. | class Solution:
def maximumGap(self, nums):
if not nums or len(nums) == 1:
return 0
sorted_gap = 0
nums = list(set(nums))
nums.sort()
for curr in range(len(nums[:-1])):
gap = nums[curr + 1] - nums[curr]
if gap > sorted_gap:
sorted_gap = gap
return sorted_gap | CLASS_DEF FUNC_DEF IF VAR FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR NUMBER VAR VAR IF VAR VAR ASSIGN VAR VAR RETURN VAR |
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Try to solve it in linear time/space. | class Solution:
def maximumGap(self, nums):
if len(nums) < 2:
return 0
minV = nums[0]
maxV = nums[0]
for i in range(len(nums)):
if nums[i] < minV:
minV = nums[i]
if nums[i] > maxV:
maxV = nums[i]
l = len(nums)
n_size = max((maxV - minV) // (l - 1), 1)
n = (maxV - minV) // n_size + 1
if n == 1:
return maxV - minV
b_max = [minV] * n
b_min = [maxV] * n
b_count = [0] * n
for i in range(l):
b_id = (nums[i] - minV) // n_size
b_count[b_id] += 1
if nums[i] > b_max[b_id]:
b_max[b_id] = nums[i]
if nums[i] < b_min[b_id]:
b_min[b_id] = nums[i]
last_max = minV
maxGap = 1
for i in range(n):
if b_count[i] > 0:
maxGap = max(maxGap, b_min[i] - last_max)
last_max = b_max[i]
return maxGap | CLASS_DEF FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER IF VAR NUMBER RETURN BIN_OP VAR VAR ASSIGN VAR BIN_OP LIST VAR VAR ASSIGN VAR BIN_OP LIST VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR VAR VAR ASSIGN VAR VAR VAR RETURN VAR |
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Try to solve it in linear time/space. | class Solution:
def maximumGap(self, nums):
n = len(nums)
if n == 0:
return 0
buckets = [{"min": None, "max": None} for _ in range(n)]
n_min = min(nums)
n_max = max(nums)
if n_max == n_min:
return 0
for num in nums:
i = (num - n_min) * (n - 1) // (n_max - n_min)
if buckets[i]["min"] is None:
buckets[i]["min"] = num
buckets[i]["max"] = num
else:
buckets[i]["min"] = min(num, buckets[i]["min"])
buckets[i]["max"] = max(num, buckets[i]["max"])
max_diff = 0
max_prev = buckets[0]["max"]
for i in range(1, n):
if buckets[i]["min"] is not None:
max_diff = max(max_diff, buckets[i]["min"] - max_prev)
max_prev = buckets[i]["max"]
return max_diff | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER RETURN NUMBER ASSIGN VAR DICT STRING STRING NONE NONE VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR RETURN NUMBER FOR VAR VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR IF VAR VAR STRING NONE ASSIGN VAR VAR STRING VAR ASSIGN VAR VAR STRING VAR ASSIGN VAR VAR STRING FUNC_CALL VAR VAR VAR VAR STRING ASSIGN VAR VAR STRING FUNC_CALL VAR VAR VAR VAR STRING ASSIGN VAR NUMBER ASSIGN VAR VAR NUMBER STRING FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR VAR STRING NONE ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR VAR STRING VAR ASSIGN VAR VAR VAR STRING RETURN VAR |
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Try to solve it in linear time/space. | class Solution:
def maximumGap(self, nums):
if len(nums) < 2:
return 0
if len(nums) == 2:
return abs(nums[0] - nums[1])
left, right = min(nums), max(nums)
brng = (right - left) // (len(nums) - 1) + 1
bnum = (right - left) // brng + 1
bucket = [None] * bnum
for x in nums:
idx = (x - left) // brng
if bucket[idx]:
bucket[idx] = min(bucket[idx][0], x), max(bucket[idx][1], x)
else:
bucket[idx] = x, x
max_gap = pre = 0
for cur in range(1, bnum):
if not bucket[cur]:
continue
max_gap = max(max_gap, bucket[cur][0] - bucket[pre][1])
pre = cur
return max_gap | CLASS_DEF FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER IF FUNC_CALL VAR VAR NUMBER RETURN FUNC_CALL VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NONE VAR FOR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR IF VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR NUMBER VAR FUNC_CALL VAR VAR VAR NUMBER VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def f(self, nums, arrS, indx, count, adj):
while arrS[indx] != nums[indx]:
nums[indx], nums[adj[arrS[indx]]] = nums[adj[arrS[indx]]], nums[indx]
adj[arrS[indx]], adj[nums[indx]] = adj[nums[indx]], adj[arrS[indx]]
indx = adj[nums[indx]]
count[0] += 1
def minSwaps(self, nums):
count = [0]
arrS = sorted(nums)
n = len(nums)
adj = {}
for i in range(n):
adj[nums[i]] = i
for i in range(n):
if nums[i] != arrS[i]:
self.f(nums, arrS, i, count, adj)
return count[0] | CLASS_DEF FUNC_DEF WHILE VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR LIST NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR RETURN VAR NUMBER |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
d = dict()
for k, v in enumerate(nums):
d[v] = k
sorted_arr = sorted(nums)
count = 0
for i in range(len(nums)):
if nums[i] != sorted_arr[i]:
count += 1
idx = d[sorted_arr[i]]
nums[i], nums[idx] = nums[idx], nums[i]
d[nums[idx]] = idx
d[nums[i]] = i
return count | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
cur = []
for i in range(n):
cur.append([nums[i], i])
cur.sort()
vis = [(False) for i in range(n)]
ans = 0
for i in range(n):
if vis[i] or cur[i][1] == i:
continue
else:
cycle_size = 0
j = i
while vis[j] == False:
vis[j] = True
j = cur[j][1]
cycle_size = cycle_size + 1
ans = ans + max(0, cycle_size - 1)
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR LIST VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
v = []
for i in range(len(nums)):
v.append((nums[i], i))
v = sorted(v)
vis = [(False) for i in range(len(nums))]
cnt = 0
for i in range(len(v)):
if vis[i] or v[i][1] == i:
continue
else:
c = 0
j = i
while vis[j] == False:
vis[j] = True
j = v[j][1]
c += 1
cnt += c - 1
return cnt | CLASS_DEF FUNC_DEF ASSIGN VAR LIST FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def sortsecond(self, val):
return val[0]
def minSwaps(self, nums):
l = []
n = len(nums)
for i in range(n):
l.append([nums[i], i])
l.sort()
c = 0
i = 0
while i < n:
if l[i][1] == i:
i += 1
continue
else:
c += 1
temp = l[i][1]
l[i], l[temp] = l[temp], l[i]
i -= 1
i += 1
return c | CLASS_DEF FUNC_DEF RETURN VAR NUMBER FUNC_DEF ASSIGN VAR LIST ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR LIST VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR NUMBER VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
L = len(nums)
A = []
for i in range(L):
A.append([nums[i], i])
A.sort()
i = 0
Ans = 0
while i < L:
if i == A[i][1]:
i += 1
continue
else:
A[A[i][1]], A[i] = A[i], A[A[i][1]]
Ans += 1
continue
return Ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR LIST VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
s = sorted(nums)
ind = {}
for i in range(n):
ind[s[i]] = i
count = 0
for i in range(n):
ii = i
while nums[ind[nums[ii]]] != nums[ii]:
jj = ind[nums[ii]]
nums[jj], nums[ii] = nums[ii], nums[jj]
count += 1
return count | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR WHILE VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, arr):
n = len(arr)
ans = 0
temp = arr.copy()
temp.sort()
dic = {}
for i in range(n):
dic[arr[i]] = i
init = 0
for i in range(n):
if arr[i] != temp[i]:
ans += 1
init = arr[i]
arr[i], arr[dic[temp[i]]] = arr[dic[temp[i]]], arr[i]
dic[init] = dic[temp[i]]
dic[temp[i]] = i
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
list1 = [[v, i] for i, v in enumerate(nums)]
list1.sort()
i = 0
count = 0
while i < len(nums):
j = list1[i][1]
if i == j:
i += 1
else:
list1[i], list1[j] = list1[j], list1[i]
count += 1
return count | CLASS_DEF FUNC_DEF ASSIGN VAR LIST VAR VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR NUMBER IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def __init__(self):
self.count = 0
def partition(self, arr, low, high):
pivot = arr[high]
pindex = low
for i in range(low, high):
if arr[i] < pivot:
arr[i], arr[pindex] = arr[pindex], arr[i]
pindex += 1
arr[high], arr[pindex] = arr[pindex], arr[high]
self.count += 1
return pindex
def quickSort(self, arr, low, high):
if low < high:
p = self.partition(arr, low, high)
self.quickSort(arr, low, p - 1)
self.quickSort(arr, p + 1, high)
def minSwaps(self, nums):
n = len(nums)
arrpos = [*enumerate(nums)]
arrpos.sort(key=lambda it: it[1])
vis = {k: (False) for k in range(n)}
ans = 0
for i in range(n):
if vis[i] or arrpos[i][0] == i:
continue
cycle_size = 0
j = i
while not vis[j]:
vis[j] = True
j = arrpos[j][0]
cycle_size += 1
if cycle_size > 0:
ans += cycle_size - 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FUNC_DEF ASSIGN VAR VAR VAR ASSIGN VAR VAR FOR VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER RETURN VAR FUNC_DEF IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR NUMBER IF VAR NUMBER VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
v = [(nums[i], i) for i in range(n)]
v.sort()
count = 0
i = 0
while i < n:
if i == v[i][1]:
i += 1
else:
count += 1
v[v[i][1]], v[i] = v[i], v[v[i][1]]
return count | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
arr = []
n = len(nums)
for i in range(n):
arr.append([nums[i], i])
arr.sort()
brr = [(0) for i in range(n)]
visited = [(False) for i in range(n)]
for i in range(n):
brr[arr[i][1]] = i
ans = 0
for i in range(n):
if visited[i] == False:
clen = 0
idx = i
while visited[idx] == False:
clen += 1
visited[idx] = True
idx = brr[idx]
ans += clen - 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR LIST ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR LIST VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, arr):
aux = [*enumerate(arr)]
aux.sort(key=lambda it: it[1])
vec = [None] * len(arr)
for idx, ele in enumerate(aux):
vec[ele[0]] = idx
visited = [False] * len(arr)
swaps = 0
for i in range(n):
visited[i] = True
nextele = vec[i]
while visited[nextele] is not True:
swaps += 1
visited[nextele] = True
i = nextele
nextele = vec[i]
return swaps | CLASS_DEF FUNC_DEF ASSIGN VAR LIST FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NONE FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR WHILE VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR ASSIGN VAR VAR VAR RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
new_sort = sorted(nums)
map = {}
for index, i in enumerate(new_sort):
map[i] = index
answer = 0
for i, item in enumerate(nums):
while i != map[item]:
temp = nums[map[item]]
nums[map[item]] = item
nums[i] = temp
item = temp
answer += 1
return answer | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR NUMBER FOR VAR VAR FUNC_CALL VAR VAR WHILE VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
d = {}
for i in range(len(nums)):
d[nums[i]] = i
a = sorted(nums)
visited = [False] * len(nums)
c = ans = 0
for i in range(len(nums)):
c = 0
j = i
while not visited[j]:
visited[j] = True
j = d[a[j]]
c += 1
if c > 0:
ans += c - 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR NUMBER IF VAR NUMBER VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
_ans = 0
nums2 = nums.copy()
nums2.sort()
_map = {}
N = len(nums2)
for i in range(N):
_map[nums[i]] = i
for i in range(N):
v1 = nums[i]
v2 = nums2[i]
if v1 == v2:
continue
else:
index = _map[v2]
nums[i], nums[index] = nums[index], nums[i]
_map[v1] = index
_ans += 1
return _ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
s = sorted(nums)
ans = 0
dic = {}
for i in range(len(nums)):
dic[s[i]] = i
i = 0
while i < len(nums):
ind = dic[nums[i]]
if i == ind:
i += 1
else:
ans += 1
nums[i], nums[ind] = nums[ind], nums[i]
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR DICT FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR IF VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
cur = [(nums[i], i) for i in range(n)]
cur.sort()
visited = [False] * n
ans = 0
for i in range(n):
if visited[i] or cur[i][1] == i:
continue
size = 0
j = i
while not visited[j]:
visited[j] = True
j = cur[j][1]
size += 1
ans += size - 1 if size > 1 else 0
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR NUMBER VAR VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
arr_copy = list(nums)
arr_copy.sort()
pos_dict = {arr_copy[i]: i for i in range(n)}
swaps = 0
visited = [False] * n
for i in range(n):
if visited[i] or nums[i] == arr_copy[i]:
continue
cycle_size = 0
j = i
while not visited[j]:
visited[j] = True
cycle_size += 1
j = pos_dict[nums[j]]
swaps += cycle_size - 1
return swaps | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR VAR VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
v = nums.copy()
m = {}
for i in range(n):
m[nums[i]] = i
v.sort()
c = 0
for i in range(n):
if v[i] != nums[i]:
in_ = m[v[i]]
nums[i], nums[in_] = nums[in_], nums[i]
m[nums[i]], m[nums[in_]] = m[nums[in_]], m[nums[i]]
c += 1
return c | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, arr):
n = len(arr)
temp = []
for i in range(0, n):
temp.append((arr[i], i))
temp.sort()
swaps = 0
for i in range(0, n):
while temp[i][0] != arr[i]:
idx = temp[i][1]
temp[i], temp[idx] = temp[idx], temp[i]
swaps += 1
return swaps | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR NUMBER VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR WHILE VAR VAR NUMBER VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
index_nums = []
res = 0
for c, i in enumerate(nums):
index_nums.append([i, c])
index_nums.sort(key=lambda x: x[0])
i = 0
while i < len(nums):
if i == index_nums[i][1]:
pass
else:
index = index_nums[i][1]
index_nums[i], index_nums[index] = index_nums[index], index_nums[i]
res += 1
i -= 1
i += 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR LIST ASSIGN VAR NUMBER FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR LIST VAR VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
arr_pos = [*enumerate(nums)]
arr_pos.sort(key=lambda x: x[1])
visited = {k: (False) for k in range(n)}
ans = 0
for i in range(n):
if visited[i] or arr_pos[i][0] == i:
continue
cycle_size = 0
j = i
while not visited[j]:
visited[j] = True
j = arr_pos[j][0]
cycle_size += 1
if cycle_size > 0:
ans += cycle_size - 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR NUMBER IF VAR NUMBER VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
ordered_nums = sorted(nums)
go_to = list()
for i in range(n):
x = nums[i]
idx = self.binarySearch(0, n - 1, x, ordered_nums)
go_to.append(idx)
visited = [False] * n
ans = 0
for i in range(n):
if visited[i] == False:
count = 0
j = i
while visited[j] == False:
visited[j] = True
count += 1
j = go_to[j]
ans += count - 1
return ans
def binarySearch(self, start, end, x, nums):
while start <= end:
mid = (start + end) // 2
if nums[mid] <= x:
start = mid + 1
else:
end = mid - 1
return start - 1 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR NUMBER ASSIGN VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR VAR BIN_OP VAR NUMBER RETURN VAR FUNC_DEF WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN BIN_OP VAR NUMBER |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
visited = [False] * n
pairs = []
for i in range(n):
pairs.append((nums[i], i))
pairs.sort()
count = 0
for i in range(n):
if visited[i] or pairs[i][1] == i:
continue
cycle_size = 0
j = i
while not visited[j]:
visited[j] = True
cycle_size += 1
j = pairs[j][1]
count += cycle_size - 1
return count | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, a):
k = [[a[i], i] for i in range(len(a))]
k.sort()
c = 0
i = 0
while i < len(a):
if i == k[i][1]:
i += 1
else:
c += 1
x = k[i][1]
temp = [0, 0]
temp[0] = k[i][0]
temp[1] = k[i][1]
k[i][0] = k[x][0]
k[i][1] = k[x][1]
k[x][0] = temp[0]
k[x][1] = temp[1]
return c | CLASS_DEF FUNC_DEF ASSIGN VAR LIST VAR VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR IF VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR LIST NUMBER NUMBER ASSIGN VAR NUMBER VAR VAR NUMBER ASSIGN VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR NUMBER VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
positions = {}
nums_sorted = sorted(nums)
for i in range(len(nums)):
positions[nums[i]] = i
n_swaps = 0
for i in range(len(nums)):
ev = nums_sorted[i]
av = nums[i]
if ev != av:
n_swaps += 1
ev_currently_at = positions[ev]
av_currently_at = i
nums[ev_currently_at], nums[av_currently_at] = (
nums[av_currently_at],
nums[ev_currently_at],
)
positions[av] = ev_currently_at
positions[ev] = i
return n_swaps | CLASS_DEF FUNC_DEF ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
swapcount = 0
d = {}
for i in range(len(nums)):
d[nums[i]] = i
keys = list(nums)
keys.sort()
i = 0
while i < len(nums):
if d[keys[i]] == i:
i += 1
else:
t = keys[i]
keys[i] = keys[d[keys[i]]]
keys[d[t]] = t
swapcount += 1
return swapcount | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR DICT FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
orig_map = {j: i for i, j in enumerate(nums)}
sorted_arr = sorted(nums)
res = 0
for i in range(len(nums)):
if nums[i] != sorted_arr[i]:
res += 1
curr = nums[i]
nums[i], nums[orig_map[sorted_arr[i]]] = (
nums[orig_map[sorted_arr[i]]],
nums[i],
)
orig_map[curr], orig_map[sorted_arr[i]] = (
orig_map[sorted_arr[i]],
orig_map[curr],
)
return res | CLASS_DEF FUNC_DEF ASSIGN VAR VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
n = len(nums)
ans = 0
tmpArr = []
for i in range(len(nums)):
tmpArr.append([nums[i], i])
tmpArr.sort()
visited = [(False) for _ in range(n)]
for i in range(n):
if visited[i] or tmpArr[i][1] == i:
continue
j = i
cycleCnt = 0
while not visited[j]:
visited[j] = True
cycleCnt += 1
j = tmpArr[j][1]
ans += cycleCnt - 1
return ans
nums.sort() | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR LIST FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR LIST VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR ASSIGN VAR VAR ASSIGN VAR NUMBER WHILE VAR VAR ASSIGN VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR BIN_OP VAR NUMBER RETURN VAR EXPR FUNC_CALL VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def swap(self, nums, i, j):
nums[i], nums[j] = nums[j], nums[i]
return
def minSwaps(self, nums):
pairs = {}
count = 0
size = len(nums)
for i in range(size):
pairs[nums[i]] = i
nums.sort()
i = 0
while i < size:
if pairs.get(nums[i]) == i:
i += 1
else:
self.swap(nums, i, pairs.get(nums[i]))
count += 1
return count | CLASS_DEF FUNC_DEF ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR RETURN FUNC_DEF ASSIGN VAR DICT ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER WHILE VAR VAR IF FUNC_CALL VAR VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR NUMBER RETURN VAR |
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 10^{5}
1 ≤ nums_{i} ≤ 10^{6} | class Solution:
def minSwaps(self, nums):
ans = 0
store = dict()
sortedArray = sorted(nums)
for i, items in enumerate(nums):
store[items] = i
for i in range(len(nums)):
if nums[i] != sortedArray[i]:
ans += 1
store[nums[i]] = store[sortedArray[i]]
nums[store[sortedArray[i]]] = nums[i]
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR RETURN VAR |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.