# Why am i getting TLE in O(n) ? Is it because of Python?

So recently I’ve been solving many of the Graphs Problems and using Python for Problem solving,
but whenever I solve problems on Codechef or HackerEarth related to graphs using Python even C++ but in some test cases in every question, it gives TLE And I am pretty sure I am not going more than O(n). Please help me out.

So like this Question it is basic bfs,dfs question, and this is My Solution 1, many people told me that it is because Python is a slow language but it doesn’t make sense to me as all these competitive programming sites consider 5X time to a python code as compared to C/C++.
The fun fact is there are many python solutions for the same Question who I think have done the same thing but didn’t get TLE for example, these Some Guy’s solution 1, Some guy’s solution 2 and Some guy’s solution 3.

It Would be a great help if you could tell me what’s the difference between these guys solution and the solution of mine or where the problem is exactly in my code (where I am consuming extra time) ?

After all this, I tried to implement it in C++ too unfortunately no magic happened it gave me TLE too. My Solution in C++.

In case you don’t want to go to those links :

My Python Solution 1:

``````    from collections import defaultdict
from collections import deque
class Graph:

def __init__ (self):
self.graph = defaultdict(list)
self.ll=0
self.flag=0
self.visit={}
self.rp={}
def creategh(self,a,b):
try:
self.rp[(a,b)]+=1
except:
self.rp[(a,b)]=1
if(a!=b):
self.graph[a].append(b)

def bfs(self,n):

dq = deque([])
self.ll=0
dq.appendleft(n)
self.visit[n]=1

while(dq):
s = dq.pop()
self.ll+=1

for i in self.graph[s]:
try:
self.visit[i] +=1

except:
self.visit[i] = 1

dq.appendleft(i)
return self.ll

g = Graph()

n,m = map(int,input().split())
x=[]
a= list(map(int,input().split()))
x.append(a)
for i in range(len(a)-1):
if(a[i]==a[i+1]):
g.creategh((0,i),(0,i+1))
g.creategh((0,i+1),(0,i))

for i in range(1,n):
a= list(map(int,input().split()))
x.append(a)
for j in range(m):

try:
if(x[i][min(j+1,m-1)]==x[i][j]):
g.creategh((i,j),(i,min(j+1,m-1)))
g.creategh((i,min(j+1,m-1)),(i,j))
except:
do="nothing"

try:
if(x[max(0,i-1)][j]==x[i][j]):
g.creategh((max(i-1,0),j),(i,j))
g.creategh((i,j),(max(i-1,0),j))
except:
do="nothing"

mmx=-999999999999999
mnxm=9999999999999999999999999999999
for i in range(n):
for j in range(m):
try:
g.visit[i]+=1
except:
lol=g.bfs((i,j))

if(lol>mmx):
mmx=lol
mnxm=x[i][j]

elif(lol==mmx):
if(mnxm>x[i][j]):
mnxm=x[i][j]

print(mnxm,mmx)
``````