Skip to content

Instantly share code, notes, and snippets.

@huynhbaoan
Created December 16, 2024 02:07
Show Gist options
  • Save huynhbaoan/a46712131507cd8dbbe166eddacc2153 to your computer and use it in GitHub Desktop.
Save huynhbaoan/a46712131507cd8dbbe166eddacc2153 to your computer and use it in GitHub Desktop.
Here are some common algorithms and problem types you might encounter in a Level 1 Codility test, along with Python code samples and explanations.
1. Find Missing Integer (Simple Counting Problem)
Problem:
Given an array of integers, find the smallest positive integer that does not appear in the array.
Example:
Input: [1, 2, 3]
Output: 4
Input: [-1, -3, 1, 2]
Output: 3
Solution:
We can use a set for efficient lookups to check if each number from 1 to len(arr)+1 exists in the array.
def find_missing_integer(arr):
# Convert the array to a set for fast lookups
num_set = set(arr)
# Check from 1 to len(arr) + 1 (the smallest possible missing integer)
for i in range(1, len(arr) + 2):
if i not in num_set:
return i
# Test cases
print(find_missing_integer([1, 2, 3])) # Output: 4
print(find_missing_integer([-1, -3, 1, 2])) # Output: 3
2. Odd Occurrences in Array
Problem:
Find the value that appears an odd number of times in the array. Assume there is exactly one such value.
Example:
Input: [9, 3, 9, 3, 9, 7, 9]
Output: 7
Solution:
We can use the XOR operator (^) because it cancels out numbers appearing an even number of times.
def find_odd_occurrence(arr):
result = 0
for num in arr:
result ^= num # XOR all numbers
return result
# Test case
print(find_odd_occurrence([9, 3, 9, 3, 9, 7, 9])) # Output: 7
Explanation:
• 9 ^ 9 = 0, 3 ^ 3 = 0, so only 7 remains.
3. Frog Jump
Problem:
A frog starts at position X and wants to get to position Y. It jumps a fixed distance D. Find the minimal number of jumps required.
Example:
Input: X = 10, Y = 85, D = 30
Output: 3
Explanation:
• Jump 1: 10 → 40
• Jump 2: 40 → 70
• Jump 3: 70 → 100
Solution:
Use simple math to calculate the number of jumps.
def frog_jump(X, Y, D):
distance = Y - X
return (distance + D - 1) // D # Equivalent to math.ceil(distance / D)
# Test case
print(frog_jump(10, 85, 30)) # Output: 3
4. Max Counter (Track Maximum)
Problem:
You have an array of counters. Given a list of operations:
• 1 ≤ A[i] ≤ N: Increase the counter at position A[i] by 1.
• A[i] = N + 1: Set all counters to the current maximum value.
Return the final state of the counters.
Example:
Input: N = 5, A = [3, 4, 4, 6, 1, 4, 4]
Output: [3, 2, 2, 4, 2]
Solution:
Efficiently track the maximum counter value without repeatedly updating all counters.
def max_counter(N, A):
counters = [0] * N
max_val = 0 # Current maximum
last_max = 0 # Last "max counter" operation
for x in A:
if 1 <= x <= N:
# Increase operation
if counters[x - 1] < last_max:
counters[x - 1] = last_max
counters[x - 1] += 1
max_val = max(max_val, counters[x - 1])
else:
# Max counter operation
last_max = max_val
# Final update to apply the last_max to all counters
for i in range(N):
if counters[i] < last_max:
counters[i] = last_max
return counters
# Test case
print(max_counter(5, [3, 4, 4, 6, 1, 4, 4])) # Output: [3, 2, 2, 4, 2]
5. Binary Gap
Problem:
Find the longest sequence of zeros surrounded by ones in the binary representation of an integer.
Example:
Input: 9 (binary: 1001)
Output: 2
Input: 32 (binary: 100000)
Output: 0 (no gap)
Solution:
Convert the number to binary, split by 1, and find the length of the largest gap.
def binary_gap(N):
binary = bin(N)[2:] # Convert to binary
gaps = binary.strip('0').split('1') # Split by '1' and remove trailing zeros
return max(len(gap) for gap in gaps)
# Test cases
print(binary_gap(9)) # Output: 2
print(binary_gap(32)) # Output: 0
6. Cyclic Rotation (Array Rotation)
Problem:
Rotate an array A K times to the right.
Example:
Input: A = [3, 8, 9, 7, 6], K = 3
Output: [9, 7, 6, 3, 8]
Solution:
Use slicing to rotate the array efficiently.
def cyclic_rotation(A, K):
if not A:
return A
K = K % len(A) # Handle cases where K > len(A)
return A[-K:] + A[:-K]
# Test case
print(cyclic_rotation([3, 8, 9, 7, 6], 3)) # Output: [9, 7, 6, 3, 8]
General Tips for Level 1 Problems:
1. Understand Constraints:
• Check the input size (N) and constraints. Simple problems might allow brute-force solutions if N is small.
2. Edge Cases to Test:
• Empty arrays or lists ([]).
• Single-element inputs.
• Inputs with duplicate values.
• Maximum/minimum possible values.
3. Optimization for Performance:
• Use sets or dictionaries for O(1) lookups.
• Avoid nested loops if N is large.
4. Write Clear Code:
• Break the problem into small steps.
• Use helper functions for repeated logic.
These problems are designed to test your ability to implement basic algorithms and use Python effectively. Practice them, and you’ll be well-prepared! Good luck!
Here’s the enhanced Python Level 1 Cheatsheet with added explanations for the logic behind each concept. This will help you understand why and when to use each feature during the test.
Python Basics Cheatsheet with Explanations
1. Input and Output
• Logic: You’ll often need to read input, process it, and print the result. For Codility tests, inputs are usually provided as single lines or space-separated values.
n = int(input()) # Read an integer input
s = input() # Read a string input
arr = list(map(int, input().split())) # Convert space-separated integers to a list
• Example Use Case:
If the input is 1 2 3 4, list(map(int, input().split())) will convert it to [1, 2, 3, 4].
2. Loops
• Logic: Loops allow you to process each element in a collection or perform a task repeatedly.
for i in range(5): # Loop from 0 to 4
print(i)
• Common Mistake: Forgetting that range(5) stops at 4, not 5.
Looping through lists:
arr = [1, 2, 3]
for num in arr:
print(num)
• When to Use: When you need to perform operations on every element of a list.
3. If-Else Conditions
• Logic: Decisions in code are made using if, elif, and else. They check conditions and execute the corresponding block of code.
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Smaller")
• Example Use Case:
Use conditions to filter numbers, classify data, or handle edge cases.
4. List Operations
• Logic: Lists are used to store multiple values. They are the most common data structure for Codility tests.
arr = [1, 2, 3, 4, 5]
print(arr[0]) # Access first element
arr.append(6) # Add element to the end
arr.pop() # Remove the last element
• Why Important: You’ll often need to process input as lists and manipulate them (e.g., sorting, removing duplicates).
Slicing:
arr[1:4] # Elements from index 1 to 3 (excludes index 4)
• Example Use Case:
Extract a sublist or reverse a list using slicing:
reversed_arr = arr[::-1]
5. String Operations
• Logic: Strings are immutable in Python, meaning you can’t modify them directly. Instead, you can create new strings using slicing and string methods.
s = "hello"
print(s.upper()) # Converts to uppercase: 'HELLO'
print(s.replace('l', 'x')) # Replaces 'l' with 'x': 'hexxo'
• Example Use Case:
Use split and join to manipulate words:
words = "this is a test".split() # ['this', 'is', 'a', 'test']
joined = " ".join(words) # 'this is a test'
6. Common Functions
• Logic: Python provides built-in functions to simplify tasks like finding the sum, minimum, or length of a list.
arr = [1, 2, 3]
print(sum(arr)) # Sum of elements
print(min(arr)) # Smallest element
print(len(arr)) # Length of the list
• Example Use Case:
Use sum to calculate the total, len to compute the average, or min/max to find extreme values in a dataset.
7. Dictionary Basics
• Logic: Dictionaries store data as key-value pairs, making lookups efficient (O(1) time complexity).
d = {"a": 1, "b": 2}
print(d["a"]) # Access value by key
d["c"] = 3 # Add a new key-value pair
• When to Use: Use dictionaries for counting frequencies or mapping relationships.
Looping through dictionaries:
for key, value in d.items():
print(key, value)
• Example Use Case: Count character occurrences in a string:
from collections import Counter
freq = Counter("hello")
print(freq) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
8. Set Basics
• Logic: Sets are useful for operations like removing duplicates or performing union/intersection.
s = {1, 2, 3}
s.add(4) # Add element
s.remove(3) # Remove element
• Example Use Case: Check for unique values:
arr = [1, 2, 2, 3]
print(len(set(arr))) # Number of unique elements: 3
9. List Comprehension
• Logic: List comprehensions create lists in a concise way.
squared = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
even = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
• When to Use: When you need to filter or transform a list in one line.
10. Functions
• Logic: Functions help you reuse code and organize logic.
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
• Example Use Case: Write functions for repetitive tasks, like checking if a number is prime or calculating Fibonacci numbers.
11. Sorting
• Logic: Sorting is often required to simplify problems (e.g., finding smallest or largest k elements).
arr = [3, 1, 4, 2]
arr.sort() # Ascending: [1, 2, 3, 4]
arr.sort(reverse=True) # Descending: [4, 3, 2, 1]
• Example Use Case:
sorted_arr = sorted(arr) # Creates a new sorted list without modifying the original
12. Error Handling
• Logic: Handle unexpected inputs to prevent your code from crashing during edge cases.
try:
x = int(input())
except ValueError:
print("Invalid input!")
• When to Use: If inputs can be invalid or operations (e.g., division by zero) may fail.
13. Time Complexity Tips
• Logic: Optimize your code to pass performance tests:
• O(1): Dictionary lookups, accessing list indices.
• O(n): Iterating through a list or string once.
• O(n log n): Sorting a list.
• O(n^2): Nested loops over the same list (avoid if input size is large).
Example of Optimization:
Instead of using a loop to count frequencies:
# Inefficient (O(n^2)):
count = 0
for x in arr:
if x == target:
count += 1
Use a dictionary (O(n)):
from collections import Counter
freq = Counter(arr)
count = freq[target]
General Problem-Solving Strategy:
1. Understand the Problem:
• Read the description carefully and identify inputs, outputs, and constraints.
2. Plan Your Approach:
• Break the problem into smaller tasks.
• Decide which data structures and algorithms to use.
3. Write Code:
• Start with a simple, correct solution.
• Optimize only if needed.
4. Test with Edge Cases:
• Try small inputs, empty lists, duplicates, or maximum constraints.
This enhanced cheatsheet covers the logic behind each concept, ensuring you’re ready for both coding and debugging during the test. Good luck!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment