Câu hỏi phỏng vấn Big-O Notation
Câu hỏi

What are some algorithms which we use daily that...

Câu trả lời

Algorithms with O(1), O(n log n), and O(log n) Complexities

O(1) - Constant Time Complexity

Algorithms with O(1) time complexity execute in a constant amount of time regardless of the input size. Here are some common examples:

  • Accessing an element in an array by index: Retrieving an element from an array using its index is done in constant time because it involves a direct memory access[5][8].
  • Pushing or popping an element from a stack: These operations are performed in constant time as they involve adding or removing an element from the top of the stack[5].
  • Checking if a number is even or odd: This can be done using a simple modulus operation, which takes constant time[5].

O(n log n) - Linearithmic Time Complexity

Algorithms with O(n log n) time complexity are common in sorting and other divide-and-conquer algorithms. Examples include:

  • Merge Sort: This sorting algorithm divides the array into halves, sorts each half, and then merges the sorted halves. The division step takes O(log n) time, and the merging step takes O(n) time, resulting in an overall complexity of O(n log n)[4][6][17].
  • Heapsort: This algorithm builds a heap from the input data and then repeatedly extracts the maximum element from the heap and rebuilds the heap. Both the heap construction and the extraction steps contribute to the O(n log n) complexity[17].
  • Quicksort (average case): This sorting algorithm selects a pivot element, partitions the array around the pivot, and recursively sorts the partitions. The partitioning step takes O(n) time, and the recursive sorting takes O(log n) time, leading to an average complexity of O(n log n)[4][6].

O(log n) - Logarithmic Time Complexity

Algorithms with O(log n) time complexity are efficient for operations that repeatedly divide the problem size by a constant factor. Examples include:

  • Binary Search: This search algorithm works on a sorted array by repeatedly dividing the search interval in half. If the target value is not found, the search interval is halved, leading to a logarithmic time complexit...
senior

senior

Gợi ý câu hỏi phỏng vấn

senior

What does it mean if an operation is O(n!) ?

middle

Why do we use Big O instead of Big Theta (Θ)?

entry

What is Big O notation?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào