Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Some Dude
Simpler O(n^2) solution (Java)?

Some Dude

Jul 18, 2023

Hi folks,

Am I missing something or is the below nested loop solution not a simpler alternative to this problem?

I understand the benefit of sliding window when you are trying to get the count, but when you have to return the sub-arrays this just seems more straight-forward?

import .*; class Solution {   public static List<List<Integer>> findSubarrays(int[] arr, int target) {     List<List<Integer>> result = new ArrayList<>();     for (int i = 0; i < ; i++) {       int product = 1;       List<Integer> temp = new ArrayList<>();       for (int j = i; j < ; j++) {         temp.add(arr[j]);         product = product * arr[j];         if (product < target) {           (new ArrayList<Integer>(temp));         } else {           break;         }       }     }     return result;   } }

2

0

Comments
Comments
A
Aniket Joshi2 years ago

im not sure i understand what is (arr[j]);? i mean i have never seen the array element wrapped in parantheses in Java. do you mind elaborating this?

Petr Gazarov
Petr Gazarov2 years ago

If there is benefit in using sliding window, I would like to know what it is. Your solution is more straight-forward. Sliding window does not reduce the time complexity.