Start learning free

LESSON 216 OF 410 · BRUTE FORCE

Longest Subarray Without Repeating (O(n^3) Time Complexity, Java)

Practice O(n3) Read the full explanation

Given an input array of integers, find the length of the longest subarray without repeating integers.

Example

Input: nums = [2, 5, 6, 2, 3, 1, 5, 6]
Output: 5
Explanation: [5, 6, 2, 3, 1] or [6, 2, 3, 1, 5] are both valid and of maximum length 5

Note:

For this lesson, your algorithm should run in O(n^3) time and use O(1) extra space.
(There exist faster solutions which we will discuss in future lessons)


STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · BRUTE FORCE

    Longest Subarray Without Reapeating in Java, explained

    Problem Definition

    The problem requires finding the length of the longest subarray in a given array of integers where no integer repeats. The input is an array of integers, and the output is a single integer representing the length of the longest subarray without repeating integers.

    Input

    • An array of integers nums.

    Output

    • An integer representing the length of the longest subarray without repeating integers.

    Constraints

    • The algorithm should run in O(n^3) time complexity.
    • The algorithm should use O(1) extra space.

    Example

    Input: nums = [2, 5, 6, 2, 3, 1, 5, 6]
    Output: 5
    Explanation: [5, 6, 2, 3, 1] or [6, 2, 3, 1, 5] are both valid and of maximum length 5

    Understanding the Problem

    The core challenge is to identify the longest contiguous subarray where all elements are unique. This problem is significant in various applications such as data stream processing, substring problems in strings, and more. A common pitfall is to overlook the need for contiguous subarrays and mistakenly consider non-contiguous subarrays.

    Approach

    To solve this problem, we can use a brute-force approach that checks all possible subarrays and determines if they contain unique elements. Although this approach is not optimal, it meets the problem's constraints of O(n^3) time complexity.

    Naive Solution

    The naive solution involves generating all possible subarrays and checking each one for uniqueness. This approach is straightforward but inefficient for large arrays.

    Optimized Solution

    While the naive solution is acceptable for this problem, we can discuss a more optimized approach for educational purposes. A sliding window technique can be used to achieve a more efficient solution, but it exceeds the given constraints.

    Algorithm

    Here is a step-by-step breakdown of the naive algorithm:

    1. Initialize a variable maxLength to store the maximum length of subarrays found.
    2. Use three nested loops to generate all possible subarrays.
    3. For each subarray, check if all elements are unique.
    4. If the subarray is unique, update maxLength if the current subarray length is greater than maxLength.
    5. Return maxLength.

    Code Implementation

    public class LongestSubarrayWithoutRepeating {
        public static int lengthOfLongestSubarray(int[] nums) {
            int maxLength = 0;
            
            // Iterate over all possible subarrays
            for (int i = 0; i < nums.length; i++) {
                for (int j = i; j < nums.length; j++) {
                    if (allUnique(nums, i, j)) {
                        maxLength = Math.max(maxLength, j - i + 1);
                    }
                }
            }
            
            return maxLength;
        }
        
        // Helper function to check if all elements in the subarray are unique
        private static boolean allUnique(int[] nums, int start, int end) {
            for (int i = start; i <= end; i++) {
                for (int j = i + 1; j <= end; j++) {
                    if (nums[i] == nums[j]) {
                        return false;
                    }
                }
            }
            return true;
        }
        
        public static void main(String[] args) {
            int[] nums = {2, 5, 6, 2, 3, 1, 5, 6};
            System.out.println("Length of the longest subarray without repeating integers: " + lengthOfLongestSubarray(nums));
        }
    }
    

    Complexity Analysis

    The time complexity of the naive approach is O(n^3) due to the three nested loops. The space complexity is O(1) as we are not using any additional data structures that grow with input size.

    Edge Cases

    Potential edge cases include:

    • An empty array: The output should be 0.
    • An array with all unique elements: The output should be the length of the array.
    • An array with all identical elements: The output should be 1.

    Examples of Edge Cases

    Input: nums = []
    Output: 0
    
    Input: nums = [1, 2, 3, 4, 5]
    Output: 5
    
    Input: nums = [1, 1, 1, 1]
    Output: 1

    Testing

    To test the solution comprehensively, consider a variety of test cases:

    • Simple cases with small arrays.
    • Edge cases as discussed above.
    • Large arrays to test performance within the given constraints.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller parts.
    • Start with a brute-force solution to understand the problem better.
    • Gradually optimize the solution by identifying and eliminating inefficiencies.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    In this blog post, we discussed the problem of finding the longest subarray without repeating integers. We explored a naive solution that meets the given constraints and provided a detailed explanation of the algorithm and its implementation in Java. Understanding and solving such problems is crucial for developing strong problem-solving skills in programming.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free