Bird
Raised Fist0
DSA Typescriptprogramming

Array Access and Update at Index in DSA Typescript

Choose your learning style10 modes available
Mental Model
An array stores items in order, and you can quickly find or change any item by its position number.
Analogy: Think of an egg carton with numbered slots; you can open any slot directly to check or replace the egg inside without touching others.
[0] 5 -> [1] 10 -> [2] 15 -> [3] 20 -> [4] 25
Dry Run Walkthrough
Input: array: [5, 10, 15, 20, 25], update value 99 at index 2
Goal: Change the value at position 2 from 15 to 99
Step 1: Access the element at index 2
[0] 5 -> [1] 10 -> [2] 15 ↑ -> [3] 20 -> [4] 25
Why: We need to find the exact position to update
Step 2: Replace the value at index 2 with 99
[0] 5 -> [1] 10 -> [2] 99 ↑ -> [3] 20 -> [4] 25
Why: Update the value at the correct position
Step 3: Finish update and return the updated array
[0] 5 -> [1] 10 -> [2] 99 -> [3] 20 -> [4] 25
Why: The array now reflects the change
Result:
[0] 5 -> [1] 10 -> [2] 99 -> [3] 20 -> [4] 25
Annotated Code
DSA Typescript
class ArrayAccessUpdate {
  private arr: number[];

  constructor(arr: number[]) {
    this.arr = arr;
  }

  updateAtIndex(index: number, value: number): void {
    if (index < 0 || index >= this.arr.length) {
      throw new Error('Index out of bounds');
    }
    // Access the element at the given index
    // Update the element with the new value
    this.arr[index] = value;
  }

  printArray(): void {
    let result = '';
    for (let i = 0; i < this.arr.length; i++) {
      result += `[${i}] ${this.arr[i]}`;
      if (i !== this.arr.length - 1) {
        result += ' -> ';
      }
    }
    console.log(result);
  }
}

// Driver code
const example = new ArrayAccessUpdate([5, 10, 15, 20, 25]);
example.updateAtIndex(2, 99);
example.printArray();
if (index < 0 || index >= this.arr.length) { throw new Error('Index out of bounds'); }
Check if index is valid to avoid errors
this.arr[index] = value;
Update the element at the given index with the new value
for (let i = 0; i < this.arr.length; i++) { ... }
Traverse the array to build a string representation
OutputSuccess
[0] 5 -> [1] 10 -> [2] 99 -> [3] 20 -> [4] 25
Complexity Analysis
Time: O(1) because accessing or updating an element by index in an array is direct and does not depend on array size
Space: O(1) because no extra space is needed besides the input array
vs Alternative: Compared to linked lists where access by position requires traversal O(n), arrays provide instant access and update at any index
Edge Cases
index is negative
Throws an error to prevent invalid access
DSA Typescript
if (index < 0 || index >= this.arr.length) { throw new Error('Index out of bounds'); }
index is equal to or greater than array length
Throws an error to prevent invalid access
DSA Typescript
if (index < 0 || index >= this.arr.length) { throw new Error('Index out of bounds'); }
array is empty
Any index access throws error because array length is zero
DSA Typescript
if (index < 0 || index >= this.arr.length) { throw new Error('Index out of bounds'); }
When to Use This Pattern
When you need to quickly find or change a value at a known position, use array access and update because it is direct and fast.
Common Mistakes
Mistake: Trying to update an index outside the array bounds without checking
Fix: Always check if the index is within 0 and array length - 1 before updating
Mistake: Confusing index with value or off-by-one errors
Fix: Remember array indexes start at 0, so the first element is at index 0
Summary
It changes the value stored at a specific position in an array.
Use it when you know the exact position of the item you want to update.
The key is that arrays let you jump directly to any position without looking at others.

Practice

(1/5)
1. What does the expression arr[2] do in an array arr?
easy
A. Accesses the element at index 2 of the array
B. Adds a new element at index 2
C. Removes the element at index 2
D. Returns the length of the array

Solution

  1. Step 1: Understand array indexing

    Arrays use zero-based indexing, so index 2 means the third element.
  2. Step 2: Access element at index 2

    The expression arr[2] retrieves the element stored at the third position.
  3. Final Answer:

    Accesses the element at index 2 of the array -> Option A
  4. Quick Check:

    arr[2] means get element at index 2 [OK]
Hint: Remember arrays start at 0, so index 2 is third element [OK]
Common Mistakes:
  • Thinking index 2 adds or removes elements
  • Confusing index with length
  • Assuming indexing starts at 1
2. Which of the following is the correct way to update the element at index 1 in a TypeScript array nums to 10?
easy
A. nums.add(1, 10);
B. nums.update(1, 10);
C. nums.set(1, 10);
D. nums[1] = 10;

Solution

  1. Step 1: Recall array element update syntax

    In TypeScript, to update an element at a specific index, use array[index] = value;.
  2. Step 2: Apply to given array

    So, nums[1] = 10; correctly updates the element at index 1 to 10.
  3. Final Answer:

    nums[1] = 10; -> Option D
  4. Quick Check:

    Use bracket notation with assignment for update [OK]
Hint: Use bracket and equals sign to update array element [OK]
Common Mistakes:
  • Using non-existent methods like update(), set(), add()
  • Confusing update syntax with other languages
  • Trying to use push() to update element
3. What will be the output of the following TypeScript code?
const arr = [5, 10, 15];
arr[1] = 20;
console.log(arr);
medium
A. [5, 10, 15]
B. [20, 10, 15]
C. [5, 20, 15]
D. [5, 15, 20]

Solution

  1. Step 1: Analyze initial array and update

    The array starts as [5, 10, 15]. The statement arr[1] = 20; changes the element at index 1 from 10 to 20.
  2. Step 2: Determine final array state

    After update, the array becomes [5, 20, 15]. The console.log prints this updated array.
  3. Final Answer:

    [5, 20, 15] -> Option C
  4. Quick Check:

    Update index 1 to 20 changes array to [5, 20, 15] [OK]
Hint: Remember index 1 is second element, update it directly [OK]
Common Mistakes:
  • Not updating the element, so output stays same
  • Mixing up indexes and values
  • Assuming update changes order
4. Identify the error in the following TypeScript code that tries to update an array element:
let fruits = ['apple', 'banana', 'cherry'];
fruits(1) = 'orange';
medium
A. Using parentheses instead of square brackets for indexing
B. Array is declared with let instead of const
C. Missing semicolon at the end of the line
D. Trying to assign a string to an array element

Solution

  1. Step 1: Check array element update syntax

    Array elements must be accessed or updated using square brackets [], not parentheses ().
  2. Step 2: Identify the error in code

    The code uses fruits(1) = 'orange'; which is invalid syntax. It should be fruits[1] = 'orange';.
  3. Final Answer:

    Using parentheses instead of square brackets for indexing -> Option A
  4. Quick Check:

    Use square brackets [] to access/update array elements [OK]
Hint: Use [] not () to access or update array elements [OK]
Common Mistakes:
  • Using parentheses instead of brackets
  • Thinking let vs const causes error here
  • Ignoring syntax errors due to missing semicolon
5. Given the array let scores = [10, 20, 30, 40, 50];, which code snippet correctly doubles the value at index 3 and then prints the updated array?
hard
A. scores[3] = scores[3] * 2; console.log(scores);
B. scores[3] *= 2; console.log(scores);
C. scores.update(3, scores[3] * 2); console.log(scores);
D. scores[3] = scores[3] + scores[3]; console.log(scores);

Solution

  1. Step 1: Understand how to double element at index 3

    Index 3 corresponds to the fourth element (value 40). Doubling means multiplying by 2.
  2. Step 2: Check each option for correct syntax and effect

    scores[3] = scores[3] * 2; console.log(scores); uses explicit multiplication and assignment, which works. scores[3] *= 2; console.log(scores); uses shorthand *= operator, also correct. scores.update(3, scores[3] * 2); console.log(scores); uses a non-existent method update(). scores[3] = scores[3] + scores[3]; console.log(scores); adds the element to itself, which also doubles it.
  3. Step 3: Identify the best concise and correct option

    scores[3] *= 2; console.log(scores); is the most concise and idiomatic way to double the value at index 3.
  4. Final Answer:

    scores[3] *= 2; console.log(scores); -> Option B
  5. Quick Check:

    Use *= operator to double value at index 3 [OK]
Hint: Use *= operator to multiply and update in one step [OK]
Common Mistakes:
  • Using non-existent update() method
  • Forgetting to print the array after update
  • Using addition instead of multiplication
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard