What is the time complexity of the following Python code snippet? Python def…

2024

What is the time complexity of the following Python code snippet?

Python

def find_element(arr, x):

for element in arr:

if element == x:

return True

return False

  1. A.

    O(log n)

  2. B.

    O(1)

  3. C.

    O(n)

  4. D.

    O(n^2)

Attempted by 140 students.

Show answer & explanation

Correct answer: C

Answer: O(n)

Explanation: The function iterates through the array and compares each element to the target until it finds a match or reaches the end. In the worst case it checks all n elements, so the time complexity is linear, O(n).

  • Worst-case: O(n) — the target is not present or is at the last position.

  • Best-case: O(1) — the target is the first element and is found immediately.

  • Average-case: O(n) — on average a constant fraction of the array is examined, which is still linear time.

Explore the full course: Coding For Placement