Top Array Interview Questions and Answers(2024)

author image Hirely
at 07 Jan, 2025

Question: How do you remove duplicates from an array?

Answer:

Removing duplicates from an array can be done in several ways, depending on the programming language and the desired efficiency. Below are common methods for removing duplicates:

1. Using a Set (for Unordered Arrays):

In most programming languages, a Set is an unordered collection of unique elements. If you convert the array to a set, duplicates will automatically be removed because sets do not allow duplicates. After conversion, you can convert it back to an array (if needed).

Example in Python:

def remove_duplicates(arr):
    return list(set(arr))

arr = [1, 2, 2, 3, 4, 4, 5]
result = remove_duplicates(arr)
print(result)  # Output: [1, 2, 3, 4, 5] (order may vary)

Example in JavaScript:

function removeDuplicates(arr) {
    return [...new Set(arr)];
}

let arr = [1, 2, 2, 3, 4, 4, 5];
let result = removeDuplicates(arr);
console.log(result);  // Output: [1, 2, 3, 4, 5]
Time Complexity:
  • Time Complexity: O(n), where n is the number of elements in the array. Converting the array to a set takes linear time, and converting it back to a list/array takes linear time.

2. Using a Dictionary (for Maintaining Order):

In some cases, maintaining the order of the original array is important. You can use a dictionary (or hash map) to track which elements you’ve already seen and only add elements that haven’t been encountered before.

Example in Python:

def remove_duplicates(arr):
    seen = {}
    result = []
    for num in arr:
        if num not in seen:
            result.append(num)
            seen[num] = True
    return result

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

Example in JavaScript:

function removeDuplicates(arr) {
    let seen = {};
    let result = [];
    for (let i = 0; i < arr.length; i++) {
        if (!seen[arr[i]]) {
            result.push(arr[i]);
            seen[arr[i]] = true;
        }
    }
    return result;
}

let arr = [1, 2, 2, 3, 4, 4, 5];
let result = removeDuplicates(arr);
console.log(result);  // Output: [1, 2, 3, 4, 5]
Time Complexity:
  • Time Complexity: O(n), where n is the number of elements in the array. Each element is visited once and added to the result only if it’s not already in the dictionary.

3. Using Sorting and Removing Consecutive Duplicates:

You can sort the array first and then iterate through it, adding elements to the result only if they are not the same as the previous element.

Example in Python:

def remove_duplicates(arr):
    arr.sort()  # Sorting the array
    result = []
    for i in range(len(arr)):
        if i == 0 or arr[i] != arr[i - 1]:
            result.append(arr[i])
    return result

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

Example in JavaScript:

function removeDuplicates(arr) {
    arr.sort();  // Sorting the array
    let result = [];
    for (let i = 0; i < arr.length; i++) {
        if (i === 0 || arr[i] !== arr[i - 1]) {
            result.push(arr[i]);
        }
    }
    return result;
}

let arr = [1, 2, 2, 3, 4, 4, 5];
let result = removeDuplicates(arr);
console.log(result);  // Output: [1, 2, 3, 4, 5]
Time Complexity:
  • Time Complexity: O(n log n) due to the sorting step, where n is the number of elements in the array.

4. Using a Simple Loop (Brute Force Method):

You can use a brute force approach where you manually check if each element is already present in the result array before adding it. This method is less efficient because it requires comparing each element with all elements in the result.

Example in Python:

def remove_duplicates(arr):
    result = []
    for num in arr:
        if num not in result:
            result.append(num)
    return result

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

Example in JavaScript:

function removeDuplicates(arr) {
    let result = [];
    for (let i = 0; i < arr.length; i++) {
        if (!result.includes(arr[i])) {
            result.push(arr[i]);
        }
    }
    return result;
}

let arr = [1, 2, 2, 3, 4, 4, 5];
let result = removeDuplicates(arr);
console.log(result);  // Output: [1, 2, 3, 4, 5]
Time Complexity:
  • Time Complexity: O(n^2), where n is the number of elements in the array, because the in or includes check takes O(n) time for each element.

Summary of Methods:

MethodTime ComplexitySpace ComplexityMaintains Order
Using SetO(n)O(n)No
Using Dictionary/Hash MapO(n)O(n)Yes
Sorting and Removing DuplicatesO(n log n)O(n)No
Brute Force Loop (Manual Check)O(n^2)O(n)Yes

Conclusion:

  • The most efficient way to remove duplicates is to use a Set (O(n) time complexity) if the order doesn’t matter.
  • If maintaining the order is important, using a Dictionary/Hash Map or a simple loop with a result array is better, both with O(n) time complexity.

Question: How do you check if an array is a palindrome?

Answer:

A palindrome is a sequence that reads the same forwards and backwards. To check if an array is a palindrome, we need to verify if the first element is equal to the last, the second element is equal to the second-last, and so on.

Steps to Check if an Array is a Palindrome:

  1. Initialize two pointers: One at the beginning (left) and one at the end (right) of the array.
  2. Compare the elements at the left and right pointers.
  3. If they are equal, move the left pointer forward (i.e., increment) and the right pointer backward (i.e., decrement).
  4. Continue this process until the left pointer is greater than or equal to the right pointer.
  5. If you find any pair of elements that are not equal, return false (the array is not a palindrome).
  6. If all pairs match, return true (the array is a palindrome).

Code Examples:

Example in Python:

def is_palindrome(arr):
    left, right = 0, len(arr) - 1
    while left < right:
        if arr[left] != arr[right]:
            return False
        left += 1
        right -= 1
    return True

# Example usage:
arr = [1, 2, 3, 2, 1]
print(is_palindrome(arr))  # Output: True

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

Example in JavaScript:

function isPalindrome(arr) {
    let left = 0, right = arr.length - 1;
    while (left < right) {
        if (arr[left] !== arr[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// Example usage:
let arr = [1, 2, 3, 2, 1];
console.log(isPalindrome(arr));  // Output: true

arr = [1, 2, 3, 4, 5];
console.log(isPalindrome(arr));  // Output: false

Time Complexity:

  • Time Complexity: O(n), where n is the number of elements in the array. We only traverse the array once, comparing pairs of elements.
  • Space Complexity: O(1), since we are using only a constant amount of extra space (two pointers).

Key Points:

  • A palindrome array is an array that is the same when read forwards and backwards.
  • The most efficient method is to use two pointers, one from the start and one from the end, and compare corresponding elements.
  • The time complexity of this approach is linear, O(n), making it very efficient for large arrays.

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