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

Coding
Easy
Infosys
134K views

Direct Answer

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 a…

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

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 80 Coding questionsBrowse all 149 Infosys questions