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.

