Python Data Structures Coding Problems

Data structures form the backbone of efficient programming. Mastering arrays, strings, and lists is essential for coding interviews and problem-solving.

This tutorial provides real-world coding problems with optimized solutions to strengthen your understanding.

1. Array Problems

Problem 1: Find Second Largest Element

Python
Second largest element
arr = list(set(map(int, input().split())))
arr.sort()
print(arr[-2])

Problem 2: Move Zeros to End

Python
Move zeros
arr = list(map(int, input().split()))

result = [x for x in arr if x != 0] + [0]*arr.count(0)
print(result)

Problem 3: Find Missing Number

Python
Missing number
n = int(input())
arr = list(map(int, input().split()))

print(n*(n+1)//2 - sum(arr))

2. String Problems

Problem 4: Count Vowels and Consonants

Python
Count vowels
s = input().lower()
vowels = 'aeiou'

v = sum(1 for c in s if c in vowels)
c = sum(1 for c in s if c.isalpha() and c not in vowels)

print("Vowels:", v, "Consonants:", c)

Problem 5: Anagram Check

Python
Anagram
s1 = input()
s2 = input()

print("Anagram" if sorted(s1) == sorted(s2) else "Not Anagram")

Problem 6: First Non-Repeating Character

Python
First unique char
s = input()

for c in s:
    if s.count(c) == 1:
        print(c)
        break

3. List Problems

Problem 7: Remove Duplicates

Python
Remove duplicates
arr = list(map(int, input().split()))
print(list(set(arr)))

Problem 8: Rotate List

Python
Rotate list
arr = list(map(int, input().split()))
k = int(input())

k = k % len(arr)
print(arr[-k:] + arr[:-k])

Problem 9: Flatten Nested List

Python
Flatten list
nested = [[1,2],[3,4],[5]]
flat = [item for sublist in nested for item in sublist]
print(flat)

4. Interview-Level Problems

Problem 10: Two Sum Problem

Python
Two sum
arr = list(map(int, input().split()))
target = int(input())

seen = {}

for i, num in enumerate(arr):
    if target - num in seen:
        print(seen[target-num], i)
        break
    seen[num] = i

Problem 11: Longest Substring Without Repeating Characters

Python
Longest substring
s = input()
char_set = set()
l = 0
max_len = 0

for r in range(len(s)):
    while s[r] in char_set:
        char_set.remove(s[l])
        l += 1
    char_set.add(s[r])
    max_len = max(max_len, r - l + 1)

print(max_len)

5. Optimization Tips

1. Use sets for faster lookup (O(1)).

2. Prefer list comprehensions for cleaner code.

3. Use built-in functions like sum(), max().

4. Optimize loops to reduce time complexity.

6. Practice Set

1. Find duplicates in array.

2. Merge two sorted arrays.

3. Check string rotation.

4. Find intersection of two arrays.

5. Kadane’s Algorithm (maximum subarray sum).

Conclusion

Mastering data structure problems in Python is essential for cracking coding interviews. Focus on understanding patterns and optimizing solutions.

Practice consistently and gradually move to more complex problems for best results.