Python Data Structures & Algorithms Flashcards
6 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 6 Python Data Structures & Algorithms flashcards as text
What is the time complexity of searching for an element in a Python dictionary?
Answer: O(1) average case
Python dictionaries use hash tables internally, providing O(1) average-case time complexity for lookups, insertions, and deletions. Worst case is O(n) due to hash collisions, but this is rare.
What is the output of the following Python code? my_list = [1, 2, 3, 4, 5] print(my_list[1:4])
Answer: [2, 3, 4]
Python list slicing with [1:4] starts at index 1 (inclusive) and ends at index 4 (exclusive), returning elements at indices 1, 2, and 3, which are [2, 3, 4].
Which Python data structure would be most efficient for implementing a FIFO (First-In-First-Out) queue?
Answer: collections.deque
collections.deque provides O(1) time complexity for both appending and popping from either end, making it ideal for FIFO queues. Lists have O(n) complexity for pop(0) operations.
What does the Python `sorted()` function return when called on a dictionary?
Answer: A sorted list of the dictionary's keys
When sorted() is called on a dictionary, it iterates over the dictionary's keys (the default iteration behavior) and returns a new sorted list of those keys.
What is a list comprehension in Python?
Answer: A concise syntax for creating lists by applying an expression to each item in an iterable
List comprehensions provide a compact way to create lists using the syntax [expression for item in iterable if condition], combining iteration, transformation, and optional filtering in a single line.
What is the difference between a Python tuple and a list?
Answer: Tuples are immutable and lists are mutable
The fundamental difference is mutability: tuples cannot be modified after creation (immutable), while lists can be changed (mutable). Tuples use parentheses () and lists use square brackets [].