How do you check if an array is sorted in a coding interview?

Coding
Easy
Infosys
134K views

This question asks candidates to verify whether an array's elements are arranged in ascending or descending order. It tests basic iteration logic, conditional checks, and understanding of array properties.

Why Interviewers Ask This

Interviewers ask this to assess fundamental programming skills and the ability to write clean, efficient code quickly. They want to see if the candidate understands how to traverse data structures and implement logical conditions correctly. This problem serves as a baseline to evaluate attention to edge cases, such as empty arrays or single-element inputs, which often trip up junior developers.

How to Answer This Question

Start by clarifying the sorting criteria, such as strictly ascending or allowing duplicates. Propose a linear scan approach with O(n) time complexity, explaining that checking adjacent elements is sufficient. Handle edge cases explicitly before writing the main loop. Finally, walk through a dry run with a sample input to demonstrate correctness and ensure your logic holds for all scenarios.

Key Points to Cover

  • Linear traversal of the array
  • Comparison of adjacent elements
  • O(n) time complexity
  • Handling edge cases

Sample Answer

To check if an array is sorted, I would iterate through the array from the first element to the second-to-last element. For each index i, I compare arr[i] with arr[i+1]. If any element is greater than the next one, the array is not sorted in ascending order, so I return false immediately. If the loop completes without finding such a pair, I return true. This approach runs in O(n) time and uses O(1) space, making it optimal. I would also handle edge cases like null or single-element arrays by returning true since they are trivially sorted.

Common Mistakes to Avoid

  • Forgetting to handle empty or single-element arrays
  • Using nested loops leading to O(n^2) complexity
  • Incorrect comparison logic for descending order

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 26 Coding questionsBrowse all 65 Infosys questions