Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort the stalls positions.
DSA Python
stalls.sort() # Sort the stalls positions positions = [1, 2, 8, 4, 9] stalls = positions stalls.[1]()
Attempts:
3 left
💡 Hint
Common Mistakes
Using reverse() instead of sort()
Trying to use sorted() without assignment
Using append() or pop() which do not sort
✗ Incorrect
We need to sort the stalls positions to apply binary search for maximum minimum distance.
2fill in blank
mediumComplete the code to check if cows can be placed with at least 'distance' apart.
DSA Python
def can_place_cows(stalls, cows, distance): count = 1 last_position = stalls[0] for i in range(1, len(stalls)): if stalls[i] - last_position >= [1]: count += 1 last_position = stalls[i] if count >= cows: return True return False
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with cows count instead of distance
Using wrong variable names in comparison
✗ Incorrect
We check if the gap between current stall and last placed cow is at least 'distance'.
3fill in blank
hardFix the error in the binary search loop condition to find maximum minimum distance.
DSA Python
def aggressive_cows(stalls, cows): stalls.sort() low = 0 high = stalls[-1] - stalls[0] result = 0 while low [1] high: mid = (low + high) // 2 if can_place_cows(stalls, cows, mid): result = mid low = mid + 1 else: high = mid - 1 return result
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' which may skip checking the last possible distance
Using '>' or '>=' which breaks the loop logic
✗ Incorrect
We use '<=' to include the case when low equals high to not miss the maximum distance.
4fill in blank
hardFill both blanks to initialize the binary search boundaries correctly.
DSA Python
def aggressive_cows(stalls, cows): stalls.sort() low = [1] high = [2] result = 0 while low <= high: mid = (low + high) // 2 if can_place_cows(stalls, cows, mid): result = mid low = mid + 1 else: high = mid - 1 return result
Attempts:
3 left
💡 Hint
Common Mistakes
Setting low to stalls[0] which is a position, not a distance
Setting high to len(stalls) which is count, not distance
✗ Incorrect
Low starts at 0 (minimum possible distance), high is max distance between first and last stall.
5fill in blank
hardFill all three blanks to complete the main function that reads input and prints the result.
DSA Python
def main(): t = int(input()) for _ in range(t): n, c = map(int, input().split()) stalls = list(map(int, input().split())) result = aggressive_cows([1], [2]) print([3]) if __name__ == '__main__': main()
Attempts:
3 left
💡 Hint
Common Mistakes
Passing n instead of c to aggressive_cows
Printing stalls or c instead of result
✗ Incorrect
We pass stalls and c to aggressive_cows and print the result variable.
