Live Jobs
NEWSoftware Engineer - Automation Tester@UplersNEWSenior Embedded Systems Software Engineer@Google India Pvt LtdNEWManager, Software Engineering - IOS - Player Team, Bangalore@Warner Bros. DiscoveryNEWSenior Software Engineer - Java@ClarivateNEWSoftware Engineer - Automation Tester@UplersSoftware Developer 2, Python Backend Developer@Kinaxis Inc.Software Developer Intern@Mexilet Technologies Private LimitedFull-Stack Software Engineer Intern - Remote@UplersSoftware Engineer, AIML - Fixed Term Contract (6 months)@NatWest GroupNEWSoftware Engineer - Automation Tester@UplersNEWSenior Embedded Systems Software Engineer@Google India Pvt LtdNEWManager, Software Engineering - IOS - Player Team, Bangalore@Warner Bros. DiscoveryNEWSenior Software Engineer - Java@ClarivateNEWSoftware Engineer - Automation Tester@UplersSoftware Developer 2, Python Backend Developer@Kinaxis Inc.Software Developer Intern@Mexilet Technologies Private LimitedFull-Stack Software Engineer Intern - Remote@UplersSoftware Engineer, AIML - Fixed Term Contract (6 months)@NatWest GroupNEWSoftware Engineer - Automation Tester@UplersNEWSenior Embedded Systems Software Engineer@Google India Pvt LtdNEWManager, Software Engineering - IOS - Player Team, Bangalore@Warner Bros. DiscoveryNEWSenior Software Engineer - Java@ClarivateNEWSoftware Engineer - Automation Tester@UplersSoftware Developer 2, Python Backend Developer@Kinaxis Inc.Software Developer Intern@Mexilet Technologies Private LimitedFull-Stack Software Engineer Intern - Remote@UplersSoftware Engineer, AIML - Fixed Term Contract (6 months)@NatWest Group

Programming LanguagesCheat Sheet

Essential code snippets and shortcuts for Python, Java, C++, C, JavaScript, TypeScript, Go, Rust, Kotlin, Swift, PHP, R, Scala, Julia, Dart, PowerShell, Bash, Terraform, YAML, HTML, CSS & SQL

22 Languages
825+ Snippets
115 Challenges
Interview Ready

1
Data Structures

List comprehension with condition

# Basic list comprehension
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)  # [0, 4, 16, 36, 64]

# Nested list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Conditional list comprehension
words = ["hello", "world", "python", "code"]
long_words = [word.upper() for word in words if len(word) > 4]
print(long_words)  # ['HELLO', 'WORLD', 'PYTHON']
Example: Create lists efficiently with filtering and transformation in one line
💡 Tip: Faster than traditional loops for simple operations
basicinterviewcoding

Dictionary comprehension

# Basic dictionary comprehension
square_dict = {x: x**2 for x in range(5)}
print(square_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Dictionary from two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)  # {'a': 1, 'b': 2, 'c': 3}

# Filter dictionary
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered = {k: v for k, v in original.items() if v > 2}
print(filtered)  # {'c': 3, 'd': 4}
Example: Create and filter dictionaries efficiently from iterables
💡 Tip: Create dictionaries efficiently from iterables
basicinterviewcoding

Set operations

set1 & set2  # intersection
set1 | set2  # union
set1 - set2  # difference
set1 ^ set2  # symmetric difference
Example: {1,2} & {2,3} = {2}, {1,2} | {2,3} = {1,2,3}
💡 Tip: Sets provide O(1) lookup and efficient set operations
basicinterviewalgorithms

Lambda functions

lambda x: x**2
sorted(data, key=lambda x: x[1])
filter(lambda x: x > 0, numbers)
map(lambda x: x*2, numbers)
Example: Anonymous functions for quick operations
💡 Tip: Use lambdas for simple one-line functions
intermediateinterviewcoding

Collections module

from collections import Counter, defaultdict, deque
Counter("hello")  # {'l': 2, 'h': 1, 'e': 1, 'o': 1}
defaultdict(list)  # auto-creates missing keys
deque([1,2,3])  # double-ended queue
Example: Specialized data structures for common use cases
💡 Tip: Counter is perfect for frequency counting problems
intermediateinterviewalgorithms

Itertools for combinations

from itertools import permutations, combinations, product
list(permutations([1,2,3], 2))  # [(1,2), (1,3), (2,1), (2,3), (3,1), (3,2)]
list(combinations([1,2,3], 2))  # [(1,2), (1,3), (2,3)]
list(product([1,2], repeat=2))  # [(1,1), (1,2), (2,1), (2,2)]
Example: Generate permutations and combinations efficiently
💡 Tip: Essential for backtracking and combinatorial problems
advancedinterviewcompetitive

2
String Manipulation

Common string methods

s.strip()  # remove whitespace
s.split(",")  # split by comma
",".join(list)  # join with comma
s.replace("old", "new")  # replace substring
s.find("sub")  # find index (-1 if not found)
Example: " hello ".strip() = "hello"
💡 Tip: strip(), split(), join() are most frequently used
basicinterviewcoding

F-string formatting

name = "Alice"
age = 25
f"Hello {name}, you are {age} years old"
f"Value: {value:.2f}"  # format to 2 decimals
f"Binary: {num:08b}"  # 8-digit binary
Example: Output: "Hello Alice, you are 25 years old"
💡 Tip: F-strings are faster and more readable than .format()
basicinterviewcoding

Regular expressions

import re
re.search(r"\d+", "abc123def")  # find digits
re.findall(r"\w+", text)  # find all words
re.sub(r"\d+", "X", text)  # replace digits with X
re.match(r"^\w+@\w+\.\w+$", email)  # email validation
Example: Pattern matching and text processing
💡 Tip: Use raw strings (r"") to avoid escaping backslashes
intermediateinterviewcoding

String slicing and validation

s[::-1]  # reverse string
s[::2]  # every 2nd character
s[1:-1]  # remove first and last
s.startswith("prefix")
s.endswith("suffix")
s.isdigit(), s.isalpha(), s.isalnum()
Example: "hello"[::-1] = "olleh"
💡 Tip: String slicing is very powerful for string manipulation
basicinterviewcoding

3
Algorithms & Data Structures

Binary search implementation

def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
Example: O(log n) search in sorted array
💡 Tip: Remember to check if array is sorted first
intermediateinterviewalgorithms

Graph traversal algorithms

# DFS (Depth-First Search)
def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    for neighbor in graph[start]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited)
    return visited

# BFS (Breadth-First Search)
from collections import deque
def bfs(graph, start):
    visited = set([start])
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return visited
Example: DFS uses recursion/stack, BFS uses queue
💡 Tip: DFS for path finding, BFS for shortest path
advancedinterviewalgorithms

Sorting techniques

# Built-in sorting
sorted([3,1,4,1,5])  # returns new list
list.sort()  # in-place sorting
sorted(data, key=lambda x: x[1])  # sort by second element
sorted(data, reverse=True)  # descending order

# Custom sorting
from functools import cmp_to_key
def compare(a, b):
    return a - b
sorted(data, key=cmp_to_key(compare))
Example: Various ways to sort data in Python
💡 Tip: Use key parameter for custom sorting logic
basicinterviewcoding

Dynamic programming patterns

# Memoization with decorator
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# Manual memoization
def fib_memo(n, memo={}):
    if n in memo:
        return memo[n]
    if n <= 1:
        return n
    memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo)
    return memo[n]
Example: Fibonacci with memoization - O(n) instead of O(2^n)
💡 Tip: @lru_cache is the easiest way to add memoization
advancedinterviewcompetitive

4
Object-Oriented Programming

Class definition with special methods

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self._private = "hidden"  # convention for private
    
    def __str__(self):
        return f"Person({self.name}, {self.age})"
    
    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"
    
    @property
    def adult(self):
        return self.age >= 18
    
    @staticmethod
    def from_string(person_str):
        name, age = person_str.split('-')
        return Person(name, int(age))
Example: Complete class with properties and static methods
💡 Tip: __str__ for user-friendly output, __repr__ for debugging
intermediateinterviewcoding

Inheritance and method overriding

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        pass

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # call parent constructor
        self.breed = breed
    
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"
Example: Animal base class with Dog and Cat subclasses
💡 Tip: Use super() to call parent class methods
intermediateinterviewcoding

Decorators for functions and classes

# Function decorator
def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end-start:.4f} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "Done"

# Class decorator
def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance
Example: Timer decorator and Singleton pattern
💡 Tip: Decorators modify behavior without changing the original function
advancedinterviewenterprise

5
Guess the Output Challenges

Late binding closure challenge

def mystery():
    x = []
    for i in range(3):
        x.append(lambda: i)
    return x

funcs = mystery()
for f in funcs:
    print(f())
🎯 Challenge: What will this code print?
💡 Tip: Think about when the lambda captures the variable i
🎯 CHALLENGEadvancedinterviewdebugging

Mutable default argument challenge

def append_to(num, target=[]):
    target.append(num)
    return target

print(append_to(12))
print(append_to(42))
🎯 Challenge: What will this code print?
💡 Tip: Consider what happens to the default list between function calls
🎯 CHALLENGEintermediateinterviewdebugging

List copying and references challenge

a = [1, 2, 3]
b = a
c = a[:]

a.append(4)
print("a:", a)
print("b:", b)
print("c:", c)
🎯 Challenge: What will this code print?
💡 Tip: Think about the difference between assignment and slicing
🎯 CHALLENGEbasicinterviewdebugging

Scope and nonlocal challenge

x = 5
def outer():
    x = 10
    def inner():
        nonlocal x
        x += 1
        return x
    return inner

func = outer()
print(func())
print(func())
print(x)
🎯 Challenge: What will this code print?
💡 Tip: Trace through the scope chain and nonlocal behavior
🎯 CHALLENGEadvancedinterviewscoping

Class vs instance variables challenge

class Counter:
    count = 0
    
    def __init__(self):
        Counter.count += 1
        self.instance_count = Counter.count

c1 = Counter()
c2 = Counter()
c3 = Counter()

print(f"c1: {c1.instance_count}, class: {Counter.count}")
print(f"c2: {c2.instance_count}, class: {Counter.count}")
print(f"c3: {c3.instance_count}, class: {Counter.count}")
🎯 Challenge: What will this code print?
💡 Tip: Consider the difference between class and instance variables
🎯 CHALLENGEintermediateinterviewoop

6
Common Pitfalls

Mutable default arguments trap

# WRONG - Mutable default argument
def add_item(item, target_list=[]):
    target_list.append(item)
    return target_list

list1 = add_item("a")  # ["a"]
list2 = add_item("b")  # ["a", "b"] - UNEXPECTED!

# CORRECT - Use None as default
def add_item(item, target_list=None):
    if target_list is None:
        target_list = []
    target_list.append(item)
    return target_list

# Alternative - Use copy
def add_item(item, target_list=None):
    target_list = target_list or []
    target_list = target_list.copy()  # Don't modify original
    target_list.append(item)
    return target_list
Example: Default mutable objects are shared between function calls
💡 Tip: Always use None as default for mutable objects
advancedinterviewdebugging

Late binding closures

# WRONG - Late binding closure
functions = []
for i in range(3):
    functions.append(lambda: i)  # All will return 2!

for f in functions:
    print(f())  # Prints: 2, 2, 2

# CORRECT - Early binding with default argument
functions = []
for i in range(3):
    functions.append(lambda x=i: x)

for f in functions:
    print(f())  # Prints: 0, 1, 2

# CORRECT - Using functools.partial
from functools import partial

def print_num(x):
    return x

functions = [partial(print_num, i) for i in range(3)]
Example: Closures capture variables by reference, not value
💡 Tip: Use default arguments or functools.partial for early binding
advancedinterviewdebugging

is vs == confusion

# WRONG - Using is for value comparison
a = 256
b = 256
print(a is b)  # True (small integers are cached)

a = 257
b = 257
print(a is b)  # False (larger integers are not cached)

# WRONG - Using == for identity
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2)  # True (same content)
print(list1 is list2)  # False (different objects)

# CORRECT usage
# Use == for value comparison
if name == "John":
    print("Hello John")

# Use is for identity comparison (None, True, False)
if value is None:
    print("No value provided")

if flag is True:  # Better: if flag:
    print("Flag is set")
Example: is checks identity, == checks equality
💡 Tip: Use is only for None, True, False, and identity checks
intermediateinterviewdebugging

Scope and iteration gotchas

# WRONG - UnboundLocalError
count = 0
def increment():
    count += 1  # UnboundLocalError!
    return count

# CORRECT - Use global keyword
count = 0
def increment():
    global count
    count += 1
    return count

# WRONG - Modifying list during iteration
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # Skips elements!

# CORRECT - Iterate over copy or use list comprehension
numbers = [1, 2, 3, 4, 5]
for num in numbers.copy():
    if num % 2 == 0:
        numbers.remove(num)

# Better - Use list comprehension
numbers = [num for num in numbers if num % 2 != 0]
Example: Variable scope and list modification during iteration
💡 Tip: Use global/nonlocal keywords and avoid modifying lists during iteration
intermediateinterviewdebugging

7
File & Exception Handling

File operations and JSON handling

# Reading files
with open("file.txt", "r") as f:
    content = f.read()  # read entire file
    lines = f.readlines()  # read all lines
    for line in f:  # iterate line by line
        print(line.strip())

# Writing files
with open("output.txt", "w") as f:
    f.write("Hello World\n")
    f.writelines(["line1\n", "line2\n"])

# JSON handling
import json
with open("data.json", "r") as f:
    data = json.load(f)
with open("output.json", "w") as f:
    json.dump(data, f, indent=2)
Example: Safe file handling with context managers
💡 Tip: Always use "with" statement for automatic file closing
basicinterviewcoding

Exception handling patterns

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (ValueError, TypeError) as e:
    print(f"Value/Type error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
    print("No exceptions occurred")
finally:
    print("This always executes")

# Custom exceptions
class CustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

raise CustomError("Something went wrong")
Example: Comprehensive error handling with custom exceptions
💡 Tip: Catch specific exceptions first, then general ones
intermediateinterviewenterprise