Day 22: Tricky String & Array Problems

Welcome to Day 22 of the Python Coding Interview Challenge! Today we cover tricky string and array problems — some of the most frequently asked questions in coding interviews. These problems test your logic, optimization skills, and knowledge of Python tricks.

📖 Concepts to Know

💡 Tricky String Interview Questions

Q1. Reverse a String without using built-in reverse()

def reverse_string(s):
    return s[::-1]

print(reverse_string("ShaiviConnect"))  # tcennoCiviahS
    

Q2. Check if a String is a Palindrome

def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome("madam"))  # True
    

Q3. Find the First Non-Repeating Character

from collections import Counter

def first_non_repeating(s):
    count = Counter(s)
    for char in s:
        if count[char] == 1:
            return char
    return None

print(first_non_repeating("aabbcde"))  # c
    

Q4. Check if Two Strings are Anagrams

def are_anagrams(s1, s2):
    return sorted(s1) == sorted(s2)

print(are_anagrams("listen", "silent"))  # True
    

Q5. Count Vowels and Consonants

def count_vowels_consonants(s):
    vowels = "aeiouAEIOU"
    v, c = 0, 0
    for ch in s:
        if ch.isalpha():
            if ch in vowels:
                v += 1
            else:
                c += 1
    return v, c

print(count_vowels_consonants("ShaiviConnect"))  # (5,7)
    

💡 Tricky Array Interview Questions

Q6. Find Missing Number in an Array

def missing_number(arr, n):
    total = n * (n + 1) // 2
    return total - sum(arr)

print(missing_number([1, 2, 4, 5], 5))  # 3
    

Q7. Find Duplicate in an Array

def find_duplicate(arr):
    seen = set()
    for num in arr:
        if num in seen:
            return num
        seen.add(num)
    return None

print(find_duplicate([1, 2, 3, 4, 2]))  # 2
    

Q8. Rotate an Array by K Steps

def rotate_array(arr, k):
    k = k % len(arr)
    return arr[-k:] + arr[:-k]

print(rotate_array([1, 2, 3, 4, 5], 2))  # [4, 5, 1, 2, 3]
    

Q9. Find Maximum Subarray Sum (Kadane’s Algorithm)

def max_subarray_sum(arr):
    max_current = max_global = arr[0]
    for num in arr[1:]:
        max_current = max(num, max_current + num)
        max_global = max(max_global, max_current)
    return max_global

print(max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]))  # 6
    

Q10. Find the Second Largest Element

def second_largest(arr):
    arr = list(set(arr))  # remove duplicates
    arr.sort()
    return arr[-2] if len(arr) >= 2 else None

print(second_largest([10, 20, 4, 45, 99]))  # 45
    

Q11. Two Sum Problem (Find indices of two numbers that add up to target)

def two_sum(nums, target):
    lookup = {}
    for i, num in enumerate(nums):
        if target - num in lookup:
            return [lookup[target - num], i]
        lookup[num] = i
    return []

print(two_sum([2,7,11,15], 9))  # [0,1]
    

✅ Key Takeaways