algoadvance

Leetcode 3095. Shortest Subarray With OR at Least K I

Problem Statement

Given an array of non-negative integers nums and an integer K, you need to find the shortest subarray with a bitwise OR sum of at least K. If there isn’t one, return -1.

Clarifying Questions

  1. Q: Are the numbers in the array guaranteed to be non-negative?
    • A: Yes, as specified.
  2. Q: Can the array be empty?
    • A: Yes, it’s possible.
  3. Q: Is the value of K guaranteed to be non-negative?
    • A: Yes, it’s guaranteed to be non-negative.
  4. Q: Could K be greater than the sum of the bitwise OR of the entire array?
    • A: Yes, it could be.

Strategy

  1. Sliding Window Technique:
    • A potential strategy involves using a sliding window to maintain the subarray and compute the bitwise OR in a dynamic fashion.
  2. Initialization:
    • Start both left and right pointers of the window at the beginning of the array.
    • Initialize a variable to keep track of the current OR value of the window.
  3. Expansion and Contraction:
    • Expand the right pointer to include more elements into the window and update the OR value.
    • Contract the left pointer if the OR value meets or exceeds K to potentially find a shorter subarray.
  4. Edge Case Handling:
    • Check immediately if the array is empty or if no subarray can meet the condition.
  5. Tracking Shortest Subarray:
    • Track the length of the shortest subarray that meets the criteria and update it during the contraction phase.

Code

public class Solution {
    public int shortestSubarrayWithORAtLeastK(int[] nums, int K) {
        // Edge case
        if (nums == null || nums.length == 0) return -1;
        
        int n = nums.length;
        int minLength = Integer.MAX_VALUE;
        int currentOR = 0;
        int left = 0;

        // Iterate over the array with the right pointer
        for (int right = 0; right < n; right++) {
            currentOR |= nums[right];

            // Contract the window while the condition is met
            while (left <= right && currentOR >= K) {
                minLength = Math.min(minLength, right - left + 1);
                currentOR &= ~nums[left];
                left++;
            }
        }

        return minLength == Integer.MAX_VALUE ? -1 : minLength;
    }
}

// Example usage
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1, 2, 3, 4, 5};
        int K = 6;
        System.out.println("Shortest subarray length: " + solution.shortestSubarrayWithORAtLeastK(nums, K)); // Output: 2
    }
}

Time Complexity

This solution iteratively adjusts a sliding window over the array and dynamically maintains the bitwise OR, making it efficient and effective for the problem at hand.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI