File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Goal: Given a positive int n, return the number of set bits in binary.
2+ # Approach:
3+ # Divide by 2 and check the remainder to determine the last bit.
4+ # If the remainder is 1, update the variable 'count'.
5+ # Repeat until n becomes 0.
6+ # Time Complexity: O(logn)
7+ # - We process each bit of n.
8+ # Space Complexity: O(1)
9+ # - We use only one variable 'count'.
10+ class Solution :
11+ def hammingWeight (self , n : int ) -> int :
12+ count = 0
13+
14+ while n != 0 :
15+ if n % 2 == 1 :
16+ count += 1
17+ n = n // 2
18+
19+ return count
Original file line number Diff line number Diff line change 1+ # Goal: Return true if it's a palindrome. If it's not, return false
2+ # - palindrome: a string that reads the same forward and backward
3+ # Time Complexity: O(n)
4+ # - Building string is O(n) + Two pointer check is O(n).
5+ # Space Complexity: O(n)
6+ # - We use a new string of size s.
7+ class Solution :
8+ def isPalindrome (self , s : str ) -> bool :
9+ chars = []
10+
11+ # Trim 's' to contain only alphanumerical characters
12+ for ch in s :
13+ if ch .isalnum ():
14+ chars .append (ch .lower ()) # make it case-insensitive
15+
16+ new_s = "" .join (chars )
17+
18+ # Use two pointers
19+ # ptr1 -> starting index ptr2 -> ending index
20+ ptr1 = 0
21+ ptr2 = len (new_s ) - 1
22+
23+ while ptr1 < ptr2 : # O(n) time
24+ # Return false if ptr1 and ptr2 point to different char
25+ if new_s [ptr1 ] != new_s [ptr2 ]:
26+ return False
27+ ptr1 += 1
28+ ptr2 -= 1
29+
30+ # Otherwise, return true
31+ return True
You can’t perform that action at this time.
0 commit comments