Array Index Safety - Problem

You are given an array of integers and a user-provided index. Your task is to safely access the array element at the given index and handle any out-of-bounds access gracefully.

Requirements:

  • If the index is valid (within array bounds), return the element at that index
  • If the index is out of bounds (negative or >= array length), return the string "Index out of bounds"
  • Use proper error handling techniques to catch and handle the exception

Note: This problem focuses on defensive programming and proper error handling when working with arrays.

Input & Output

Example 1 — Valid Index
$ Input: arr = [5,2,8,1], index = 2
Output: 8
💡 Note: Index 2 is valid (within bounds 0-3), so return arr[2] = 8
Example 2 — Index Too Large
$ Input: arr = [5,2,8,1], index = 6
Output: Index out of bounds
💡 Note: Index 6 is greater than array length 4, so return error message
Example 3 — Negative Index
$ Input: arr = [10,20,30], index = -1
Output: Index out of bounds
💡 Note: Negative index -1 is invalid, so return error message

Constraints

  • 1 ≤ arr.length ≤ 104
  • -109 ≤ arr[i] ≤ 109
  • -106 ≤ index ≤ 106

Visualization

Tap to expand
INPUTALGORITHMRESULT528Array: [5, 2, 8]Index: 51Check Bounds25 >= 3? YES3Return ErrorOutput:Index out of boundsKey Insight:Validate array boundaries before access to prevent runtime errors and improve performanceTutorialsPoint - Array Index Safety | Boundary Check Approach
Asked in
Google 15 Amazon 12 Microsoft 10
12.5K Views
Medium Frequency
~8 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen