File tree Expand file tree Collapse file tree 5 files changed +93
-0
lines changed
longest-palindromic-substring
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 5 files changed +93
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def validTree (self , n : int , edges : List [List [int ]]) -> bool :
3+ # filter false cases by definition of tree
4+ if n - 1 != len (edges ):
5+ return False
6+
7+ nodes = set ()
8+
9+ for i , edge in enumerate (edges ):
10+ nodes .add (edge [0 ])
11+ nodes .add (edge [1 ])
12+
13+ if i + 1 > len (nodes ) - 1 :
14+ return False
15+
16+ return True
17+
18+ ## TC: O(num(edges)), SC: P(num(nodes))
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def rob (self , nums : List [int ]) -> int :
3+ n = len (nums )
4+ if n == 1 :
5+ return nums [0 ]
6+
7+ def robrob (nums ):
8+ rob1 , rob2 = 0 , 0
9+ for i in range (len (nums )):
10+ rob1 , rob2 = rob2 , max (nums [i ] + rob1 , rob2 )
11+
12+ return rob2
13+
14+ return max (robrob (nums [:n - 1 ]), robrob (nums [1 :]))
15+
16+ ## TC: O(n), SC: O(1)
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def rob (self , nums : List [int ]) -> int :
3+ rob , not_rob = 0 , 0
4+
5+ for i in nums :
6+ rob , not_rob = not_rob + i , max (rob , not_rob )
7+
8+ return max (rob , not_rob )
9+
10+ ## TC: O(n), SC: O(1)
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def longestPalindrome (self , s : str ) -> str :
3+ if s == s [::- 1 ]:
4+ return s
5+
6+ start , max_length = 0 , 1
7+
8+ for i in range (1 , len (s )):
9+ odd_s = i - max_length - 1
10+ even_s = i - max_length
11+ odd_p = s [odd_s :i + 1 ]
12+ even_p = s [even_s :i + 1 ]
13+
14+ if odd_s >= 0 and odd_p == odd_p [::- 1 ]:
15+ start = odd_s
16+ max_length += 2
17+ elif even_p == even_p [::- 1 ]:
18+ start = even_s
19+ max_length += 1
20+
21+ return s [start :start + max_length ]
22+
23+ ## TC: O(n^2), SC: O(1)
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def countComponents (self , n : int , edges : List [List [int ]]) -> int :
3+
4+ graph = collections .defaultdict (list )
5+
6+ for x , y in edges :
7+ graph [x ].append (y )
8+ graph [y ].append (x )
9+
10+ def dfs (node , visited ):
11+ visited .add (node )
12+ for neighbor in graph [node ]:
13+ if neighbor not in visited :
14+ dfs (neighbor , visited )
15+
16+ count = 0
17+ visited = set ()
18+
19+ for node in range (n ):
20+ if node not in visited :
21+ dfs (node , visited )
22+ count += 1
23+
24+ return count
25+
26+ ## TC && SC: O(num(edge) + num(node))
You can’t perform that action at this time.
0 commit comments