Hackerrank Python Data Structures & Algorithms ā Questions and Answers
Question 1: What is the time complexity of searching for an element in a Python dictionary?
- O(1) average case (Correct answer)
- O(n)
- O(log n)
- O(n²)
Correct 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.
Question 2: What is the output of the following Python code? my_list = [1, 2, 3, 4, 5] print(my_list[1:4])
- [2, 3, 4] (Correct answer)
- [1, 2, 3, 4]
- [2, 3, 4, 5]
- [1, 2, 3]
Correct 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].
Question 3: Which Python data structure would be most efficient for implementing a FIFO (First-In-First-Out) queue?
- collections.deque (Correct answer)
- list
- set
- tuple
Correct 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.
Question 4: What does the Python `sorted()` function return when called on a dictionary?
- A sorted list of the dictionary's keys (Correct answer)
- A sorted dictionary
- A sorted list of the dictionary's values
- A sorted list of key-value tuples
Correct 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.
Question 5: What is a list comprehension in Python?
- A concise syntax for creating lists by applying an expression to each item in an iterable (Correct answer)
- A method for sorting lists in place
- A way to convert lists to dictionaries
- A function that counts elements in a list
Correct 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.
Question 6: What is the difference between a Python tuple and a list?
- Tuples are immutable and lists are mutable (Correct answer)
- Tuples can only store integers
- Lists are faster than tuples for all operations
- Tuples use curly braces and lists use square brackets
Correct 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 [].
What is the time complexity of searching for an element in a Python dictionary?