ask me a hackerrank type of question
- User
ask me a hackerrank type of question
- Assistant
Sure! Here's a HackerRank-style programming problem for you:
ask me a hackerrank type of question
Sure! Here's a HackerRank-style programming problem for you:
Given a binary array arr consisting of only 0s and 1s, find the length of the longest contiguous subarray with an equal number of 0s and 1s.
n, the size of the array.n space-separated integers (each of which is either 0 or 1).arr is either 0 or 1.6
0 1 0 1 0 1
6
The entire array has three 0s and three 1s.
4
0 0 1 1
4
The entire array has two 0s and two 1s.
5
0 1 0 1 0
4
The longest subarray with equal number of 0s and 1s is from index 0 to index 3 or from index 1 to index 4.
Consider using a hash map to store the first occurrence of a cumulative count. Increment the count by +1 for every 1 and decrement by -1 for every 0. If the same cumulative count occurs again, the subarray between these two indices has equal numbers of 0s and 1s.
Here’s a Python solution using a hash map to achieve linear time complexity:
def findMaxLength(arr):
count_map = {0: -1} # Initialize with count 0 at index -1
max_length = 0
count = 0
for i, num in enumerate(arr):
# Treat 0 as -1 and 1 as +1
count += -1 if num == 0 else 1
if count in count_map:
max_length = max(max_length, i - count_map[count])
else:
count_map[count] = i
return max_length
# Read input
n_and_rest = []
try:
while True:
line = input()
if line.strip() == "":
break
n_and_rest.append(line.strip())
except EOFError:
pass
n = int(n_and_rest[0])
arr = list(map(int, n_and_rest[1].split()))
print(findMaxLength(arr))
Feel free to try solving the problem! Let me know if you need any hints or solutions.
Not yet included in a published release.