HackerRank study Flashcards
Data structures
If we have a tree of n nodes, how many edges will it have?
n-1
Data Structures
Which of the following data structures can handle updates and queries in log(n) time on an array?
Segment Tree
Data structures
Of the following data structures, which has a Last in First Out ordering?(LIFO) In other words, the one that came in last will be the first to be popped.
Stack
A stack works on the principle where the last element added is the first to be removed. It’s like a stack of plates; you remove the top plate first, which was the last one placed
Data structures
Of the following data structures, which has a First In First Out (FIFO) ordering? In other words, the one that came in first will be the first to be removed.
Queue
In a queue, the element that is added first to the collection is the first one to be removed. This ordering is analogous to how people queue up for services, where the first person to line up is the first to receive service and leave.
True or False: “/” is float division.
True
True or False: “//” is integer division.
True
What do you call this expression?
newlist = [expression for item in iterable if condition == True]
list comprehension
Overloading
What is the output of the following Python code snippet?
class Printer:
def print_number(self, a, b=1):
return a + b
p = Printer()
output = p.print_number(5)
6
What does method overloading refer to in Python?
A) Defining multiple methods outside the class with the same name
B) Defining multiple methods within the class with the same name but different parameters
C) Changing the behavior of built-in Python operators
D) Using multiple classes with the same method name
Defining multiple methods within the class with the same name but different parameters
Which of the following is a correct way to simulate method overloading in Python?
A) Using multiple methods with the same name but different numbers of required parameters
B) Using default parameters in methods
C) Defining methods in different modules
D) Python supports method overloading by default
Using default parameters in methods
overloading
Consider the following code:
class Display:
def show(self, message=”Hello”, times=1):
for _ in range(times):
print(message)
What happens when the method show is called as show(“Goodbye”, 3) on an instance of Display?
A) It prints “Hello” 1 time
B) It prints “Goodbye” 3 times
C) It prints “Goodbye” 1 time
D) It results in an error
It prints “Goodbye” 3 times
Which statement about overloading in Python is true?
A) Python allows different methods in the same class to have the same name as long as their parameter types are different.
B) Overloading in Python can only be implemented using external libraries.
C) Python uses the last defined method if multiple methods have the same name and number of parameters.
D) Python natively supports method overloading like Java or C++.
Python uses the last defined method if multiple methods have the same name and number of parameters.
Define O(1)
Constant Time: An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size. For example, accessing any element in an array by index is an O(1) operation.
Define O(n)
Linear Time: An algorithm runs in linear time when the execution time increases linearly with the input size. For example, finding the maximum element in an unsorted array requires looking at each element, resulting in O(n) time complexity.
Define O(log n)
Logarithmic Time: Logarithmic time complexity occurs when the algorithm reduces the input data size by a constant factor (usually half) with each step. Binary search is a classic example, where each step cuts the search space in half, resulting in O(log n) time complexity.
Define O(n^2)
Quadratic Time: This complexity arises when an algorithm involves a double loop over the data. For example, a simple bubble sort on an array has O(n^2) time complexity because it iterates over the array for each element.
Define O(n log n)
This is often seen in more efficient sorting algorithms like quicksort and mergesort, where the algorithm divides the data (log n) and then performs linear work at each division (n).
O(2^n) and O(n!)
These are seen in algorithms that grow extremely fast with input size, often making them impractical for large inputs. Examples include certain recursive algorithms like calculating Fibonacci numbers naively or solving the traveling salesman problem via brute force.
What o notation is this
Accessing an Array Element
def get_first_element(array):
return array[0]
Accessing the first element is an O(1) constant time
What o notation is this
Checking if a Dictionary is Empty
def is_empty(dictionary):
return not dictionary
Checking emptiness is O(1) because it’s a direct property check.
What o notation is this
Incrementing a Number
def increment(number):
return number + 1
Incrementing a number is an O(1) operation.
What o notation is this
Setting a Value in a Dictionary
def set_value(dictionary, key, value):
dictionary[key] = value
Setting an item in a dictionary is O(1) on average.
What o notation is this
Return a Constant
def return_constant():
return 42
Returning a constant is an O(1) operation.
What o notation is this
Checking a Boolean Flag
def check_flag(flag):
if flag:
return “True”
else:
return “False”
Checking a flag is an O(1) operation.
What o notation is this
Multiplying Two Numbers
def multiply(a, b):
return a * b
Multiplication of two numbers is O(1).
What o notation is this
Print a Static String
def print_message():
print(“Hello, World!”)
Printing a fixed message is an O(1) operation.
What o notation is this
Adding an Element to the Beginning of a List
def add_to_front_of_list(lst, element):
lst.insert(0, element)
Adding to the front of a list is O(1) in Python’s list implementation.
What o notation is this
Swap Two Elements in an Array
def swap_elements(arr, index1, index2):
arr[index1], arr[index2] = arr[index2], arr[index1]
Swapping elements is an O(1) operation.
What is the time complexity of accessing any specific element in an array by index?
A) O(n)
B) O(1)
C) O(log n)
D) O(n^2)
O(1)
Which operation is an example of O(1) complexity?
A) Searching for an element in a sorted array using binary search
B) Calculating the sum of all elements in an array
C) Inserting a new node in a linked list, given a reference to the position
D) Returning the first element of a list
Returning the first element of a list
Setting a key-value pair in a Python dictionary is generally considered to have which time complexity?
A) O(1)
B) O(n)
C) O(log n)
D) O(n log n)
O(1)
What is the time complexity of printing a fixed string, regardless of input size?
A) O(n)
B) O(log n)
C) O(1)
D) O(n^2)
O(1)
Which of the following operations has O(1) space complexity?
A) Creating a new list proportional to input size
B) Incrementing an integer variable
C) Storing all input values in a new list
D) Appending elements to a list while iterating over another list of the same size
Incrementing an integer variable
What is the time complexity of checking if a number is even or odd?
A) O(n)
B) O(log n)
C) O(1)
D) O(n^2)
O(1)
Which of the following operations typically has a constant time complexity in a hash table?
A) Deleting a key-value pair
B) Searching for an element based on its key
C) Resizing the hash table when it is full
D) Iterating over all elements
Searching for an element based on its key
What is the time complexity of assigning a value to a variable in a program?
A) O(n)
B) O(1)
C) O(log n)
D) O(n log n)
O(1)
What o notation is this
Binary Search
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
O(log n)
What o notation is this
Balanced Binary Tree
def height_of_bst(node):
if node is None:
return 0
return 1 + max(height_of_bst(node.left), height_of_bst(node.right))
O(log n)
Calculating Power Using Exponentiation by Squaring
What o notation is this
def power(base, exp):
if exp == 0:
return 1
half = power(base, exp // 2)
if exp % 2 == 0:
return half * half
else:
return base * half * half
O(log n)
What o notation is this
Finding the Largest Power of 2 Less Than or Equal to N
def largest_power_of_two(n):
power = 1
while power * 2 <= n:
power *= 2
return power
O(log n)
What o notation is this
Binary Reduction of an Array Sum
def binary_reduction_sum(arr):
while len(arr) > 1:
new_arr = []
for i in range(0, len(arr), 2):
if i + 1 < len(arr):
new_arr.append(arr[i] + arr[i+1])
else:
new_arr.append(arr[i])
arr = new_arr
return arr[0]
O(n log n) — note: while this involves reducing the problem size by half each iteration, the overall complexity involves processing each element multiple times.
What o notation is this
Recursive Halving
def recursive_halving(n):
if n <= 1:
return n
return recursive_halving(n // 2)
O(log n)
What o notation is this
Iterative Log Base 2
def iterative_log_base2(n):
count = 0
while n > 1:
n //= 2
count += 1
return count
O(log n)
Which operation in a binary search tree (BST) generally has a time complexity of O(log n)?
A) Inserting an element in a balanced BST
B) Traversing all elements in a BST
C) Adding an element to an unbalanced BST
D) Deleting all elements from a BST
Inserting an element in a balanced BST
What is the time complexity of searching for an element in a sorted array using binary search?
A) O(1)
B) O(n)
C) O(log n)
D) O(n log n)
O(log n)
In a balanced binary tree, the time complexity to reach the deepest node is:
A) O(n)
B) O(log n)
C) O(n log n)
D) O(1)
O(log n)
What o notation is this
Summing Array Elements
def sum_array(arr):
total = 0
for num in arr:
total += num
return total
O(n)
what o notation is this
Checking for Uniqueness in a List
def is_unique(lst):
seen = set()
for x in lst:
if x in seen:
return False
seen.add(x)
return True
O(n)
what o notation is this
Linear Search
def linear_search(arr, target):
for index, value in enumerate(arr):
if value == target:
return index
return -1
O(n)
What o notation is this
Counting Characters in a String
def count_chars(s):
count = {}
for char in s:
if char in count:
count[char] += 1
else:
count[char] = 1
return count
O(n)
What o notation is this
Find Maximum in an Array
def find_max(arr):
max_val = arr[0]
for num in arr:
if num > max_val:
max_val = num
return max_val
O(n)
What o notation is this
Reverse a String
def reverse_string(s):
return ‘‘.join(reversed(s))
O(n)
What O notation is this
Validate a Sequence
def validate_sequence(seq):
return all(seq[i] <= seq[i+1] for i in range(len(seq) - 1))
O(n)
What O notation is this
Print Elements
def print_elements(elements):
for element in elements:
print(element)
O(n)
What O notation is this
Calculate Fibonacci Using Iteration
def fib_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
O(n)
Big O notation
Filter Even Numbers
def filter_evens(numbers):
return [num for num in numbers if num % 2 == 0]
O(n)
What is the time complexity of finding the largest number in an unsorted list?
O(n)
Which of these operations has O(n) time complexity?
A) Searching for an element in a sorted array using binary search
B) Calculating the sum of all elements in an array
C) Inserting an element at the beginning of a linked list
D) Accessing an element by index in an array
B) Calculating the sum of all elements in an array
What is the time complexity of reversing a string of length n?
O(n)
What is the time complexity of checking if all elements in an array are unique?
O(n)
What is the time complexity of an algorithm that counts the frequency of each character in a string?
O(n)