Problem : https://practice.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos1401/1#
My code is added below. It runs perfectly well on my machine as well as when I compile & run on the GFG. But when I submit the code, it gives me error on the same input which was cleared in compile & run.
I have added the output of both compile & run and submit.


How Come it is printing the array bigger than its size?
#User function Template for python3
def updatePosIndex(array, pos_index,n,k):
for index in range(pos_index+k,n):
if array[index] >= 0:
pos_index = index
break
return pos_index
def updateNegIndex(array, neg_index,n, k):
for index in range(neg_index+k,n):
if array[index] < 0:
neg_index = index
break
return neg_index
def twoPointer(array,n):
pos_index = updatePosIndex(array, 0, n, 0)
neg_index = updateNegIndex(array, 0, n, 0)
flag = 1
for i in range(n):
if flag == 1:
if array[i] < 0:
array[i], array[pos_index] = array[pos_index], array[i]
neg_index = updateNegIndex(array, neg_index,n, 1)
pos_index = updatePosIndex(array, pos_index,n, 1)
elif flag == -1:
if array[i] >= 0:
array[i], array[neg_index] = array[neg_index], array[i]
pos_index = updatePosIndex(array, pos_index,n, 1)
neg_index = updateNegIndex(array, neg_index,n, 1)
flag = flag*-1
return array
class Solution:
def rearrange(self,arr, n):
arr = twoPointer(arr,n)
arr = arr[:n]
return arr
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
tc = int(input())
while tc > 0:
n = int(input())
arr = list(map(int, input().strip().split()))
ob = Solution()
ob.rearrange(arr, n)
for x in arr:
print(x, end=" ")
tc -= 1
# } Driver Code Ends
Note: I don't want alternate solutions. I want to know why this problem exists and how to prevent it in future.
There are two issues:
First (Minor) you must alter the arr list inside the rearrange method and there is no need to return any value. take a look at the driver code. there is no assignment there. so you only need to change the arr list inside the rearrange method.
Second (Major), also there is a bug inside the GeeksForGeeks judge system. when the driver prints the output of the previous runs it won't clear the buffer and unfortunately the new input and old outputs merge together so the judge system misevaluates the results.
to overcome these problems I've changed the Solution class a bit:
Flag = False
class Solution:
def rearrange(self,arr, n):
global Flag
twoPointer(arr,n)
if Flag == True:
print()
else:
Flag = True
now, your code passes the first test case successfully. but seems that it won't run correctly over the second result. but this is another issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With