Top Array Interview Questions

author image Hirely
at 07 Jan, 2025

Question: What are the different types of arrays in programming?

Answer:

Arrays are fundamental data structures used to store collections of elements. Depending on how the elements are organized and accessed, arrays can be classified into various types. Below are the most common types of arrays in programming:


1. One-Dimensional Arrays (1D Arrays)

  • Definition: A one-dimensional array is the simplest form of an array, where elements are stored in a linear sequence. It can be thought of as a list or a single row of elements.

  • Access: Each element is accessed using a single index.

    Example (C++):

    int arr[] = {10, 20, 30, 40, 50};
    cout << arr[2];  // Output: 30

    Example (Python):

    arr = [10, 20, 30, 40, 50]
    print(arr[2])  # Output: 30

2. Multi-Dimensional Arrays (MD Arrays)

  • Definition: A multi-dimensional array is an array of arrays, where each element is itself an array. These are used to represent more complex data structures like matrices or grids.
  • Access: You use multiple indices to access an element, such as array[i][j] for a 2D array, array[i][j][k] for a 3D array, etc.

2.1 Two-Dimensional Arrays (2D Arrays)

  • A 2D array can be visualized as a matrix (rows and columns).

    Example (C++):

    int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
    cout << arr[1][2];  // Output: 6

    Example (Python):

    arr = [[1, 2, 3], [4, 5, 6]]
    print(arr[1][2])  # Output: 6

2.2 Three-Dimensional Arrays (3D Arrays)

  • A 3D array can be visualized as a “cube” with depth, rows, and columns.

    Example (C++):

    int arr[2][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
    cout << arr[1][0][1];  // Output: 6

    Example (Python):

    arr = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
    print(arr[1][0][1])  # Output: 6

3. Jagged Arrays (Array of Arrays)

  • Definition: A jagged array (also known as an array of arrays) is an array where each element is a reference to another array, and each of these inner arrays can have different lengths.

  • Access: Like multi-dimensional arrays, but the inner arrays can vary in size.

    Example (C#):

    int[][] arr = new int[3][];
    arr[0] = new int[] {1, 2, 3};
    arr[1] = new int[] {4, 5};
    arr[2] = new int[] {6, 7, 8, 9};
    Console.WriteLine(arr[1][1]);  // Output: 5

    Example (JavaScript):

    let arr = [[1, 2, 3], [4, 5], [6, 7, 8, 9]];
    console.log(arr[1][1]);  // Output: 5
  • Key Difference: In jagged arrays, each sub-array (row) can have different lengths, unlike 2D or 3D arrays where the size is uniform.


4. Dynamic Arrays

  • Definition: A dynamic array is an array whose size can grow or shrink during runtime. Languages like Python, JavaScript, and Java provide dynamic arrays (also known as lists or array lists) that automatically resize when elements are added or removed.

  • Key Feature: Dynamic arrays manage memory internally and automatically resize as needed, which allows you to store an arbitrary number of elements.

    Example (Python):

    arr = [1, 2, 3]
    arr.append(4)  # Adds 4 to the array
    print(arr)  # Output: [1, 2, 3, 4]

    Example (JavaScript):

    let arr = [1, 2, 3];
    arr.push(4);  // Adds 4 to the array
    console.log(arr);  // Output: [1, 2, 3, 4]
  • Underlying Mechanism: When a dynamic array reaches its capacity, it may allocate more memory and copy the elements to a new, larger memory space.


5. Associative Arrays (Hashmaps, Dictionaries)

  • Definition: Associative arrays are arrays where each element is stored as a key-value pair, rather than an indexed position. These are commonly known as hashmaps or dictionaries in many programming languages.

  • Access: Elements are accessed using keys rather than indices.

    Example (Python - Dictionary):

    arr = {"a": 1, "b": 2, "c": 3}
    print(arr["b"])  # Output: 2

    Example (JavaScript - Object or Map):

    let arr = {a: 1, b: 2, c: 3};
    console.log(arr["b"]);  // Output: 2
  • Use Case: Useful for looking up values based on unique keys, providing efficient searching and retrieval.


6. Circular Arrays

  • Definition: A circular array (or ring buffer) is an array where the last element is connected to the first element, forming a “circle”. It is typically used in scenarios like queues, where the array “wraps around” when the end is reached.

  • Key Feature: It allows efficient use of array space by reusing the first positions when elements are removed, making it useful for applications like buffer management.

    Example (C++):

    // Circular buffer simulation
    int arr[5] = {1, 2, 3, 4, 5};
    int start = 0, end = 4;
    // Wrap-around behavior
    start = (start + 1) % 5;  // Move to next position

7. Sparse Arrays

  • Definition: A sparse array is an array in which most of the elements have the default value (such as null, 0, or undefined). Only a few elements are populated with actual data, which makes sparse arrays memory-efficient in cases where the array has a lot of empty or default values.

  • Key Feature: Typically implemented using hashmaps or associative arrays internally.

    Example (JavaScript):

    let sparseArray = [];
    sparseArray[100] = "Hello";  // Only the element at index 100 is set
    console.log(sparseArray[100]);  // Output: Hello

8. Fixed-Size Arrays (Static Arrays)

  • Definition: A fixed-size array is an array where the size is determined at compile time (in languages like C, C++, or Java). The size of the array cannot be changed once it is initialized.

  • Key Feature: These arrays do not dynamically resize and typically have a predefined size that cannot be altered during runtime.

    Example (C++):

    int arr[5] = {1, 2, 3, 4, 5};

Summary Table:

TypeDescriptionExample Use Case
One-Dimensional (1D)A simple linear array of elements.Storing a list of numbers.
Two-Dimensional (2D)Array of arrays, used to represent matrices.Storing matrix data.
Three-Dimensional (3D)Array of arrays of arrays, used for 3D grids.Storing 3D grid data.
Jagged ArrayAn array of arrays with varying lengths.Storing lists of different lengths.
Dynamic ArrayArray whose size can grow and shrink at runtime.Storing an unknown number of elements.
Associative ArrayArray where elements are stored as key-value pairs.Storing mappings (like a dictionary).
Circular ArrayArray where the end wraps around to the beginning.Queue or buffer management.
Sparse ArrayArray

where most elements are undefined or empty. | Representing sparse data, like matrices with few non-zero elements. | | Fixed-Size Array | Array with a predefined, unchangeable size. | Storing a fixed number of items. |


Conclusion:

Each type of array has its specific use case, and choosing the right type of array depends on the problem you’re trying to solve. For example, dynamic arrays are useful when you don’t know the size in advance, while multi-dimensional arrays are perfect for representing matrices or grids.

Question: How do you reverse an array?

Answer:

Reversing an array means rearranging its elements in the opposite order. There are several ways to reverse an array depending on the programming language and method. Below are examples in different languages and approaches.


1. Reversing an Array in JavaScript

  • Using the reverse() method: JavaScript arrays come with a built-in reverse() method that reverses the array in place (modifies the original array).

    Example:

    let arr = [1, 2, 3, 4, 5];
    arr.reverse();
    console.log(arr);  // Output: [5, 4, 3, 2, 1]
  • Using a loop to reverse an array manually: If you prefer not to mutate the original array, you can create a new array and reverse it using a loop.

    Example:

    let arr = [1, 2, 3, 4, 5];
    let reversedArr = [];
    
    for (let i = arr.length - 1; i >= 0; i--) {
      reversedArr.push(arr[i]);
    }
    
    console.log(reversedArr);  // Output: [5, 4, 3, 2, 1]

2. Reversing an Array in Python

  • Using the reverse() method: Python lists have an in-place reverse() method that directly modifies the original list.

    Example:

    arr = [1, 2, 3, 4, 5]
    arr.reverse()
    print(arr)  # Output: [5, 4, 3, 2, 1]
  • Using slicing to reverse: You can reverse an array by using Python’s slicing feature.

    Example:

    arr = [1, 2, 3, 4, 5]
    reversed_arr = arr[::-1]
    print(reversed_arr)  # Output: [5, 4, 3, 2, 1]

3. Reversing an Array in Java

  • Using the Collections.reverse() method: In Java, you can use Collections.reverse() to reverse a list. Note that this works for List and not primitive arrays.

    Example:

    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    public class ReverseArray {
      public static void main(String[] args) {
        Integer[] arr = {1, 2, 3, 4, 5};
        List<Integer> list = Arrays.asList(arr);
        Collections.reverse(list);
        System.out.println(list);  // Output: [5, 4, 3, 2, 1]
      }
    }
  • Using a for loop to reverse: If you’re dealing with a primitive array, you can reverse it manually using a loop.

    Example:

    public class ReverseArray {
      public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        for (int i = 0; i < arr.length / 2; i++) {
          int temp = arr[i];
          arr[i] = arr[arr.length - 1 - i];
          arr[arr.length - 1 - i] = temp;
        }
        
        System.out.println(Arrays.toString(arr));  // Output: [5, 4, 3, 2, 1]
      }
    }

4. Reversing an Array in C++

  • Using a for loop to reverse: In C++, you can manually reverse an array by swapping elements from the front and back.

    Example:

    #include <iostream>
    using namespace std;
    
    int main() {
      int arr[] = {1, 2, 3, 4, 5};
      int n = sizeof(arr) / sizeof(arr[0]);
      
      for (int i = 0; i < n / 2; i++) {
        int temp = arr[i];
        arr[i] = arr[n - 1 - i];
        arr[n - 1 - i] = temp;
      }
      
      for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";  // Output: 5 4 3 2 1
      }
      
      return 0;
    }

5. Reversing an Array in C

  • Using a for loop to reverse: In C, similar to C++, you can reverse the array in-place by swapping elements from the front and back.

    Example:

    #include <stdio.h>
    
    int main() {
      int arr[] = {1, 2, 3, 4, 5};
      int n = sizeof(arr) / sizeof(arr[0]);
      
      for (int i = 0; i < n / 2; i++) {
        int temp = arr[i];
        arr[i] = arr[n - 1 - i];
        arr[n - 1 - i] = temp;
      }
      
      for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);  // Output: 5 4 3 2 1
      }
      
      return 0;
    }

6. Reversing an Array in Ruby

  • Using the reverse method: Ruby provides a reverse method that creates a new array with the elements in reverse order.

    Example:

    arr = [1, 2, 3, 4, 5]
    reversed_arr = arr.reverse
    puts reversed_arr.inspect  # Output: [5, 4, 3, 2, 1]

7. Reversing an Array in Go

  • Using a for loop to reverse: Go does not have a built-in function for reversing arrays, but you can use a simple loop to reverse the elements.

    Example:

    package main
    import "fmt"
    
    func main() {
      arr := []int{1, 2, 3, 4, 5}
      for i := 0; i < len(arr)/2; i++ {
        arr[i], arr[len(arr)-1-i] = arr[len(arr)-1-i], arr[i]
      }
      fmt.Println(arr)  // Output: [5 4 3 2 1]
    }

Conclusion:

The method you choose to reverse an array depends on the programming language and whether you want to modify the original array or create a new one. Most languages provide built-in functions or methods to reverse arrays, but you can also achieve this manually using loops for more control or to avoid modifying the original array.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as Array interview questions, Array interview experiences, and details about various Array job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now