709013. Bitwise AND of the Array

Medium

Bitwise AND of the Array

Summary

Given an array of integers, find the bitwise AND of all elements in the array. The problem requires a deep understanding of bitwise operations and their properties.

Detailed Explanation

The key to solving this problem is to understand how bitwise AND works. The bitwise AND operation compares each bit of the first operand (the left-hand operand) to the corresponding bit of the second operand (the right-hand operand). If both bits are 1, then the corresponding result bit is set to 1. Otherwise, the result bit is set to 0.

To solve this problem, we need to iterate through the array and perform a bitwise AND operation on each element with the current maximum bitwise AND value. The maximum bitwise AND value should be initialized as the first element of the array. Then, for each subsequent element, update the maximum bitwise AND value by performing a bitwise AND operation between the current element and the previous maximum bitwise AND value.

Here's the step-by-step breakdown:

  1. Initialize max_and as the first element of the array.
  2. Iterate through the array starting from the second element (index 1).
  3. For each element, update max_and by performing a bitwise AND operation between the current element and max_and.
  4. Return max_and.

The time complexity of this solution is O(n), where n is the number of elements in the array. The space complexity is O(1) as we only use a constant amount of space.

Here's an ASCII art diagram to illustrate the process:

  +---------------+
  |    Array     |
  +---------------+
           |
           v
  +---------------+
  |   max_and = arr[0] |
  +---------------+
           |
           v
  +---------------+
  | Loop through array: |
  |    for i = 1 to n-1: |
  |        max_and = max_and & arr[i] |
  +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
public int findBitwiseAnd(int[] nums) {
    int maxAnd = nums[0];
    for (int num : nums) {
        maxAnd &= num;
    }
    return maxAnd;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.