I have an array of numbers of size n, select all possible distinct increasing subsequence of the array, for each subsequence find the bitwise OR value and return them as result in increasing order.
Example:
arr= [4,2,4,1], n = 4
Result
[1,2,4,6]
Explanation:
All possible distinct increasing subsequences are:
[4]
[2]
[2, 4]
[1]
Bit wise or values are:
[4]
[2]
[2 | 4] = [6]
[1]
So values are [2,4,6, 1]
sorted result is [1,2,4,6]
Another Example:
arr = [3,2,4,6], n = 4
Result
[2,3,4,6,7]
Explanation:
All increasing subsequences and corresponding bitwise or values are:
[3] : 3
[3, 4] : 7
[3, 4, 6] : 7
[3, 6] : 7
[2] : 2
[2, 4] : 6
[2, 4, 6] : 6
[2, 6] : 6
[4] : 4
[4, 6] : 6
[6] : 6
So distinct values are [3,7,2,6,4]
sorted result is [2,3,4,6,7]
Constraints:
1 <= n <= 10^4
1 <= arr[i] <= 1024
I have solved it using brute force approach, here is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {3,2,4,6};
List<List<Integer>> subsequences = findIncreasingSubsequences(arr);
Set<Integer> set = new TreeSet<>();
for (List<Integer> subsequence : subsequences) {
int or = subsequence.get(0);
for(int i=1; i<subsequence.size(); i++) {
or |= subsequence.get(i);
}
//System.out.println(subsequence + " : "+ or);
set.add(or);
}
System.out.println("Result : " + set);
}
public static List<List<Integer>> findIncreasingSubsequences(int[] arr) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> current = new ArrayList<>();
findSubsequences(arr, result, current, 0);
return result;
}
private static void findSubsequences(int[] arr, List<List<Integer>> result, List<Integer> current, int start) {
if (!current.isEmpty()) {
result.add(new ArrayList<>(current)); // Add current subsequence to result
}
for (int i = start; i < arr.length; i++) {
if (current.isEmpty() || arr[i] > current.get(current.size() - 1)) {
current.add(arr[i]);
findSubsequences(arr, result, current, i + 1);
current.remove(current.size() - 1);
}
}
}
}
How to solve this in less time complexity.