For Given Number N find if its COLORFUL number or not
Return 0/1
COLORFUL number:
A number can be broken into different contiguous sub-subsequence parts.
Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245.
And this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different
Example:
N = 23
2 3 23
2 -> 2
3 -> 3
23 -> 6
this number is a COLORFUL number since product of every digit of a sub-sequence are different.
Output : 1
Solution:
Time: O(n^3) Space: O(n^2)
public class Solution { public int colorful(int A) { List<Integer> list = new ArrayList<>(); while (A > 0) { int val = A % 10; list.add(val); A = A / 10; } Collections.reverse(list); Set<Integer> products = new HashSet<>(); for (int len = 1; len <= list.size(); len ++) { for (int i = 0; i <= list.size() - len; i ++) { int j = i; int product = 1; while (j < i + len) { product *= list.get(j); j ++; } if (!products.add(product)) { return 0; } } } return 1; } }