Google Interview Question
Software EngineersCountry: United States
package findSubArray;
import java.util.*;
public class findSubArray {
public static int findsubArray(int arr[], int k) {
int n = arr.length, i, j;
int array[][] = new int[n][n];
for(i=0;i<n;i++) {
array[0][i] = arr[i];
}
for(i=0;i<n;i++) {
array[i][0] = arr[0];
}
for(i=1; i<n; i++) {
for(j=i;j<n;j++) {
array[i][j] = arr[j] * array[i-1][j-1];
System.out.println("i: "+i+" j: "+j+" arr[i-1][j-1]: "+array[i-1][j-1]+" arr[i][j]: "+array[i][j]);
if(array[i][j] % k ==0) {
if(i != 0) {
System.out.println("End of subarray is: "+arr[j]);
return i+1;
}
}
}
}
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int array[] = {1, 9, 16, 5, 4, 3, 2};
int k = 720;
int answer = findsubArray(array, k);
System.out.println("Minimum lenth of subarray is: "+answer);
}
}
If those the number of those lamps fits into an integer of some sort (or really, this requirement could be just the ranges you flip), I think this solution could work too (not tested):
int get_range(unsigned long n, int i, int j) {
return (n >> i) & ((1 << j) - 1);
}
int flip(unsigned long n, int i, int j) {
return n + (~get_range(n, i, j) - get_range(n, i, j));
}
int isOn(unsigned long n, int i) {
return n & (1 << i);
}
Space O(N), Update O(1) if the bitwise operators are O(1) as expected, query O(1)
hasSumMultK :: (Map.Map Int Int) -> Int ->[Int] -> Int-> Bool
hasSumMultK m s [] _ = Map.member s m
hasSumMultK m sum (x:xs) k = let newSum = (sum + x) `mod` k
in (Map.member sum m) ||
hasSumMultK (Map.insert sum sum m) newSum xs k
hasSumMultOfK :: [Int] -> Int -> Bool
hasSumMultOfK = hasSumMultK Map.empty 0
Looking for help on interview preparation?
Visit AONECODE.COM for ONE-TO-ONE private lessons by FB, Google and Uber engineers!
Customized course covers
System Design (for candidates of FB, LinkedIn, AMZ, Google and Uber etc)
Algorithms (DP, Greedy, Graph etc. every aspect you need in a coding interview and Clean Coding)
Interview questions sorted by companies
Mock Interviews
Our members got into G, U, FB, Amazon, LinkedIn, MS and other top-tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
- aonecoding January 13, 2018