Home > Software design >  I cannot understand why this code is wrong
I cannot understand why this code is wrong

Time:02-14

class Solution:
    
    def firstRepeated(self,A, n):
        
        #arr : given array
        #n : size of the array
        
        D={}
        for i in range(n):
            if A[i] not in D:
                D[A[i]]=[i]
            else: 
                D[A[i]].append(i)
        c=0
        for i in D:
            if(len(D[i])>1):
                c =1
                return (D[i][0] 1)
            
        if(c==0): return -1
       
A=[1 ,5 ,3, 4, 3, 5, 6]

n=len(A)

M=Solution()

print(M.firstRepeated(A,n))

this is a problem from geeks for geeks. " Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest"

the index positions(returned) are assumed to start from 1. If there is no such element that has frequency more than 1 , we gotta return -1

This code is actually working correctly in VS code, but whenever I use it in GFG IDE, it's failing(shows 3 as output instead of 2)

Kindly help, as I have no idea what's wrong here.

CodePudding user response:

Your code is returning the index of the repeating element based on the order that keys are stored in the dictionary. After having collected all values in a dictionary keyed by number, your code iterates that dictionary like this:

    for i in D:

The order in which this loop will visit the dictionary keys (indexes), depends on the Python version. See result in geeksforgeeks

  • Related