■ 20 Most Important LeetCode Loop Problems
1108. Defanging an IP Address
■ Loop through string and replace '.' with '[.]'.
class Solution:
def defangIPaddr(self, address: str) -> str:
result = ""
for c in address:
if c == '.':
result += "[.]"
else:
result += c
return result
58. Length of Last Word
■ Loop from back skipping spaces until a word is found.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i, length = len(s)-1, 0
while i >= 0 and s[i] == ' ':
i -= 1
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length
268. Missing Number
■ Use formula sum(0..n) and subtract array sum using a loop.
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
total = n * (n + 1) // 2
return total - sum(nums)
344. Reverse String
■ Use two-pointer loop from both ends to reverse array.
class Solution:
def reverseString(self, s: List[str]) -> None:
l, r = 0, len(s)-1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1; r -= 1
412. Fizz Buzz
■ Loop 1..n and check divisibility by 3 and 5.
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
ans.append("FizzBuzz")
elif i % 3 == 0:
ans.append("Fizz")
elif i % 5 == 0:
ans.append("Buzz")
else:
ans.append(str(i))
return ans
136. Single Number
■ Loop with XOR to cancel out duplicates.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for x in nums:
ans ^= x
return ans
509. Fibonacci Number
■ Loop to generate Fibonacci instead of recursion.
class Solution:
def fib(self, n: int) -> int:
if n < 2: return n
a, b = 0, 1
for _ in range(2, n+1):
a, b = b, a+b
return b
191. Number of 1 Bits
■ Loop shifting bits and counting set bits.
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
count += n & 1
n >>= 1
return count
9. Palindrome Number
■ Loop to reverse number and compare with original.
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
rev, num = 0, x
while num:
rev = rev*10 + num%10
num //= 10
return rev == x
67. Add Binary
■ Loop from right of both strings, manage carry.
class Solution:
def addBinary(self, a: str, b: str) -> str:
i, j, carry, ans = len(a)-1, len(b)-1, 0, ""
while i >= 0 or j >= 0 or carry:
s = carry
if i >= 0: s += int(a[i]); i -= 1
if j >= 0: s += int(b[j]); j -= 1
ans += str(s % 2)
carry = s // 2
return ans[::-1]
70. Climbing Stairs
■ Classic DP but solved with loop like Fibonacci.
class Solution:
def climbStairs(self, n: int) -> int:
a, b = 1, 1
for _ in range(n):
a, b = b, a+b
return a
125. Valid Palindrome
■ Loop with two pointers, skip non-alnum chars.
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s)-1
while l < r:
while l < r and not s[l].isalnum(): l += 1
while l < r and not s[r].isalnum(): r -= 1
if s[l].lower() != s[r].lower():
return False
l, r = l+1, r-1
return True
26. Remove Duplicates from Sorted Array
■ Loop with two pointers to keep unique elements.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums: return 0
j = 0
for i in range(1, len(nums)):
if nums[i] != nums[j]:
j += 1
nums[j] = nums[i]
return j+1
27. Remove Element
■ Loop and overwrite values not equal to val.
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
j = 0
for i in range(len(nums)):
if nums[i] != val:
nums[j] = nums[i]
j += 1
return j
66. Plus One
■ Loop from back, handle carry if digit=9.
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
for i in reversed(range(len(digits))):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
return [1] + digits
14. Longest Common Prefix
■ Loop character by character among all strings.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return ""
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
if not prefix: return ""
return prefix
28. Implement strStr()
■ Loop to check substring occurrence.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle: return 0
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
35. Search Insert Position
■ Loop to find position of target.
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for i, num in enumerate(nums):
if num >= target:
return i
return len(nums)
169. Majority Element
■ Loop with Boyer-Moore Voting algorithm.
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count, candidate = 0, None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate