perfect squares leetcode - recursive solution with memoization - java

Trying to solve this problem with recursion and memoization but for input 7168 I'm getting wrong answer.
public int numSquares(int n) {
Map<Integer, Integer> memo = new HashMap();
List<Integer> list = fillSquares(n, memo);
if (list == null)
return 1;
return helper(list.size()-1, list, n, memo);
}
private int helper(int index, List<Integer> list, int left, Map<Integer, Integer> memo) {
if (left == 0)
return 0;
if (left < 0 || index < 0)
return Integer.MAX_VALUE-1;
if (memo.containsKey(left)) {
return memo.get(left);
}
int d1 = 1+helper(index, list, left-list.get(index), memo);
int d2 = 1+helper(index-1, list, left-list.get(index), memo);
int d3 = helper(index-1, list, left, memo);
int d = Math.min(Math.min(d1,d2), d3);
memo.put(left, d);
return d;
}
private List<Integer> fillSquares(int n, Map<Integer, Integer> memo) {
int curr = 1;
List<Integer> list = new ArrayList();
int d = (int)Math.pow(curr, 2);
while (d < n) {
list.add(d);
memo.put(d, 1);
curr++;
d = (int)Math.pow(curr, 2);
}
if (d == n)
return null;
return list;
}
I'm calling like this:
numSquares(7168)
All test cases pass (even complex cases), but this one fails. I suspect something is wrong with my memoization but cannot pinpoint what exactly. Any help will be appreciated.

You have the memoization keyed by the value to be attained, but this does not take into account the value of index, which actually puts restrictions on which powers you can use to attain that value. That means that if (in the extreme case) index is 0, you can only reduce what is left with one square (1²), which rarely is the optimal way to form that number. So in a first instance memo.set() will register a non-optimal number of squares, which later will get updated by other recursive calls which are pending in the recursion tree.
If you add some conditional debugging code, you'll see that map.set is called for the same value of left multiple times, and with differing values. This is not good, because that means the if (memo.has(left)) block will execute for cases where that value is not guaranteed to be optimal (yet).
You could solve this by incorporating the index in your memoization key. This increases the space used for memoization, but it will work. I assume you can work this out.
But according to Lagrange's four square theorem every natural number can be written as the sum of at most four squares, so the returned value should never be 5 or more. You can shortcut the recursion when you get passed that number of terms. This reduces the benefit of using memoization.
Finally, there is a mistake in fillSquares: it should add n itself also when it is a perfect square, otherwise you'll not find solutions that should return 1.

Not sure about your bug, here is a short dynamic programming Solution:
Java
public class Solution {
public static final int numSquares(
final int n
) {
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
int j = 1;
int min = Integer.MAX_VALUE;
while (i - j * j >= 0) {
min = Math.min(min, dp[i - j * j] + 1);
++j;
}
dp[i] = min;
}
return dp[n];
}
}
C++
// Most of headers are already included;
// Can be removed;
#include <iostream>
#include <cstdint>
#include <vector>
#include <algorithm>
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
#define MAX INT_MAX
using ValueType = std::uint_fast32_t;
struct Solution {
static const int numSquares(
const int n
) {
if (n < 1) {
return 0;
}
static std::vector<ValueType> count_perfect_squares{0};
while (std::size(count_perfect_squares) <= n) {
const ValueType len = std::size(count_perfect_squares);
ValueType count_squares = MAX;
for (ValueType index = 1; index * index <= len; ++index) {
count_squares = std::min(count_squares, 1 + count_perfect_squares[len - index * index]);
}
count_perfect_squares.emplace_back(count_squares);
}
return count_perfect_squares[n];
}
};
int main() {
std::cout << std::to_string(Solution().numSquares(12) == 3) << "\n";
return 0;
}
Python
Here we can simply use lru_cache:
class Solution:
dp = [0]
#functools.lru_cache
def numSquares(self, n):
dp = self.dp
while len(dp) <= n:
dp += min(dp[-i * i] for i in range(1, int(len(dp) ** 0.5 + 1))) + 1,
return dp[n]
Here are LeetCode's official solutions with comments:
Java: DP
class Solution {
public int numSquares(int n) {
int dp[] = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
// bottom case
dp[0] = 0;
// pre-calculate the square numbers.
int max_square_index = (int) Math.sqrt(n) + 1;
int square_nums[] = new int[max_square_index];
for (int i = 1; i < max_square_index; ++i) {
square_nums[i] = i * i;
}
for (int i = 1; i <= n; ++i) {
for (int s = 1; s < max_square_index; ++s) {
if (i < square_nums[s])
break;
dp[i] = Math.min(dp[i], dp[i - square_nums[s]] + 1);
}
}
return dp[n];
}
}
Java: Greedy
class Solution {
Set<Integer> square_nums = new HashSet<Integer>();
protected boolean is_divided_by(int n, int count) {
if (count == 1) {
return square_nums.contains(n);
}
for (Integer square : square_nums) {
if (is_divided_by(n - square, count - 1)) {
return true;
}
}
return false;
}
public int numSquares(int n) {
this.square_nums.clear();
for (int i = 1; i * i <= n; ++i) {
this.square_nums.add(i * i);
}
int count = 1;
for (; count <= n; ++count) {
if (is_divided_by(n, count))
return count;
}
return count;
}
}
Java: Breadth First Search
class Solution {
public int numSquares(int n) {
ArrayList<Integer> square_nums = new ArrayList<Integer>();
for (int i = 1; i * i <= n; ++i) {
square_nums.add(i * i);
}
Set<Integer> queue = new HashSet<Integer>();
queue.add(n);
int level = 0;
while (queue.size() > 0) {
level += 1;
Set<Integer> next_queue = new HashSet<Integer>();
for (Integer remainder : queue) {
for (Integer square : square_nums) {
if (remainder.equals(square)) {
return level;
} else if (remainder < square) {
break;
} else {
next_queue.add(remainder - square);
}
}
}
queue = next_queue;
}
return level;
}
}
Java: Most efficient solution using math
Runtime: O(N ^ 0.5)
Memory: O(1)
class Solution {
protected boolean isSquare(int n) {
int sq = (int) Math.sqrt(n);
return n == sq * sq;
}
public int numSquares(int n) {
// four-square and three-square theorems.
while (n % 4 == 0)
n /= 4;
if (n % 8 == 7)
return 4;
if (this.isSquare(n))
return 1;
// enumeration to check if the number can be decomposed into sum of two squares.
for (int i = 1; i * i <= n; ++i) {
if (this.isSquare(n - i * i))
return 2;
}
// bottom case of three-square theorem.
return 3;
}
}

Related

How to encode a number using its prime factors in java using arrays?

I have this question I am trying to solve
I wrote this code
public static int[] encodeNumber(int n) {
int count = 0, base = n, mul = 1;
for (int i = 2; i < n; i++) {
if(n % i == 0 && isPrime(i)) {
mul *= i;
count++;
if(mul == n) {
break;
}
n /= i;
}
}
System.out.println("count is " + count);
int[] x = new int[count];
int j = 0;
for (int i = 2; i < base; i++) {
if(n % i == 0 && isPrime(i)) {
mul *= i;
x[j] = i;
j++;
if(mul == n) break;
n /= i;
}
break;
}
return x;
}
public static boolean isPrime(int n) {
if(n < 2) return false;
for (int i = 2; i < n; i++) {
if(n % i == 0) return false;
}
return true;
}
I am trying to get the number of its prime factors in a count variable and create an array with the count and then populate the array with its prime factors in the second loop.
count is 3
[2, 0, 0]
with an input of 6936. The desired output is an array containing all its prime factors {2, 2, 2, 3, 17, 17}.
Your count is wrong, because you count multiple factors like 2 and 17 of 6936 only once.
I would recommend doing it similar to the following way, recursively:
(this code is untested)
void encodeNumberRecursive(int remainder, int factor, int currentIndex, Vector<Integer> results) {
if(remainder<2) {
return;
}
if(remainder % factor == 0) {
results.push(factor);
remainder /= factor;
currentIndex += 1;
encodeNumberRecursive(remainder , factor, currentIndex, results);
} else {
do {
factor += 1;
} while(factor<remainder && !isPrime(factor));
if(factor<=remainder) {
encodeNumberRecursive(remainder , factor, currentIndex, results);
}
}
}
Finally, call it with
Vector<Integer> results = new Vector<Integer>();
encodeNumberRecursive(n, 2, 0, results);
You can also do it without recursion, I just feel it is easier.
Well here is a piece of code I would start with. It is not finished yet and I did not test it, but that's the way you should go basically.
// First find the number of prime factors
int factorsCount = 0;
int originalN = n;
while (n > 1) {
int p = findLowestPrimeFactor(n);
n /= p;
factorsCount++;
}
// Now create the Array of the appropriate size
int[] factors = new int[factorsCount];
// Finally do the iteration from the first step again, but now filling the array.
n = originalN;
int k = 0;
while (n > 1) {
int p = findLowestPrimeFactor(n);
factors[k] = p;
k++;
n = n / p;
}
return factors;
Having found a factor (on increasing candidates), you can assume it is prime,
if you divide out the factor till the candidate no longer is a factor.
Your problem is not repeatedly dividing by the factor.
public static int[] encodeNumber(int n) {
if (n <= 1) {
return null;
}
List<Integer> factors = new ArrayList<>();
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) { // i is automatically prime, as lower primes done.
factors.add(i);
n /= i;
}
}
return factors.stream().mapToInt(Integer::intValue).toArray();
}
Without data structures, taking twice the time:
public static int[] encodeNumber(int n) {
if (n <= 1) {
return null;
}
// Count factors, not storing them:
int factorCount = 0;
int originalN = n;
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) {
++factorCount;
n /= i;
}
}
// Fill factors:
n = originalN;
int[] factors = new int[factorCount];
factorCount = 0;
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) {
factors[factorCount++] = i;
n /= i;
}
}
return factors;
}

Making a recursive function iterative

Assignment: Compute an according to the formulas:
a0 = 1
a1 = 3
a2 = 5
an = an-1 * a2n-2 * a3n-3
I am having trouble making the function iterative. I figured out how to do it recursively. How would I go about doing it specifically for this task and just in general?
My code for the recursive:
public static BigInteger recurs(int bigInteger){
BigInteger sum;
if (bigInteger == 0) {
sum = new BigInteger(String.valueOf("1"));
} else if (bigInteger == 1) {
sum = new BigInteger(String.valueOf("3"));
} else if (bigInteger == 2) {
sum = new BigInteger(String.valueOf("5"));
} else {
sum = recurs(bigInteger-1).multiply(recurs(bigInteger-2).pow(2).multiply(recurs(bigInteger-3).pow(3)));
}
return sum;
}
You need to remember the last three values and compute a new one each time in terms of the last one.
public static BigInteger iter(int n) {
BigInteger a = BigInteger.valueOf(1);
BigInteger b = BigInteger.valueOf(3);
BigInteger c = BigInteger.valueOf(5);
switch (n) {
case 0: return a;
case 1: return b;
case 2: return c;
default:
for (int i = 2; i < n; i++) {
BigInteger next = c.multiply(b.pow(2)).multiply(a.pow(3));
a = b;
b = c;
c = next;
}
return c;
}
}
Note this is O(n) instead of O(n^3)
To give you a hint:
Initialize an array of size n which will hold the answers. For example, ith index will store the answer for a_i. Initialize a_0, a_1 and a_2 to the values given to you (1,3 and 5 in your case). Now start iterating from index 3 onwards and use your formula to calculate a_i.
You have to store your last three results in three variables and apply the formula on these. Below you can find a simplified example using int. You can enhance this code by using BigInteger so it will work for larger numbers as well.
static int compute_iterative(int n) {
if (n == 0) return 1;
if (n == 1) return 3;
if (n == 2) return 5;
int a_n3 = 1;
int a_n2 = 3;
int a_n1 = 5;
int a_n = a_n1;
int i = 3;
while (i <= n) {
a_n = a_n1 * (int) Math.pow(a_n2, 2) * (int) Math.pow(a_n3, 3);
a_n3 = a_n2;
a_n2 = a_n1;
a_n1 = a_n;
i++;
}
return a_n;
}
Version using BigInterger:
static BigInteger compute_iterative(int n) {
if (n < 0) {
throw new IllegalArgumentException("Unsupported input value: " + n);
}
final BigInteger[] values = { BigInteger.valueOf(1), BigInteger.valueOf(3), BigInteger.valueOf(5) };
if (n < values.length) {
return values[n];
}
int i = 3;
while (i <= n) {
final BigInteger result = values[2].multiply(values[1].pow(2)).multiply(values[0].pow(3));
values[0] = values[1];
values[1] = values[2];
values[2] = result;
i++;
}
return values[2];
}

Java fastest way to get cardinality of BitSet intersection

The function below takes two BitSets, makes a copy of the first (it must not be overridden), intersects the copy with the second (bitwise AND) and returns the cardinality of the result.
public int getIntersectionSize(BitSet bits1, BitSet bits2) {
BitSet copy = (BitSet) bits1.clone();
copy.and(bits2);
return copy.cardinality();
}
I'm interested if this code can be sped up? This function is called billion of times so even a microsecond speed up makes sense plus I'm curious about the fastest possible code.
If you're going to use each BitSet several times, it could be worthwhile to create a long array corresponding to each BitSet. For each BitSet:
long[] longs = bitset.toLongArray();
Then you can use the following method, which avoids the overhead of creating a cloned BitSet. (This assumes that both arrays are the same length).
int getIntersectionSize(long[] bits1, long[] bits2) {
int nBits = 0;
for (int i=0; i<bits1.length; i++)
nBits += Long.bitCount(bits1[i] & bits2[i]);
return nBits;
}
Here is an alternative version, but I'm not sure if it is really faster, depends on nextSetBit.
public int getIntersectionsSize(BitSet bits1, BitSet bits2) {
int count = 0;
int i = bits1.nextSetBit(0);
int j = bits2.nextSetBit(0);
while (i >= 0 && j >= 0) {
if (i < j) {
i = bits1.nextSetBit(i + 1);
} else if (i > j) {
j = bits2.nextSetBit(j + 1);
} else {
count++;
i = bits1.nextSetBit(i + 1);
j = bits2.nextSetBit(j + 1);
}
}
return count;
}
The above is the readable version, hopefully good enough for the compiler, but you could optimize it manually I guess:
public int getIntersectionsSize(BitSet bits1, BitSet bits2) {
int count = 0;
for (int i = bits1.nextSetBit(0), j = bits2.nextSetBit(0); i >= 0 && j >= 0; ) {
while (i < j) {
i = bits1.nextSetBit(i + 1);
if (i < 0)
return count;
}
if (i == j) {
count++;
i = bits1.nextSetBit(i + 1);
}
while (j < i) {
j = bits2.nextSetBit(j + 1);
if (j < 0)
return count;
}
if (i == j) {
count++;
j = bits2.nextSetBit(j + 1);
}
}
return count;
}
I've been looking for a solution to this recently and here's what I came up with:
int intersectionCardinality(final BitSet lhs, final BitSet rhs) {
int lhsNext;
int retVal = 0;
int rhsNext = 0;
while ((lhsNext = lhs.nextSetBit(rhsNext)) != -1 &&
(rhsNext = rhs.nextSetBit(lhsNext)) != -1) {
if (rhsNext == lhsNext) {
retVal++;
rhsNext++;
}
}
return retVal;
}
Perhaps someone would like to take the time to compare the different solutions here and post the results...

Codility - Counting Elements Lessons : fastest algorithm swap

i am studying Codility chapter 2 : Counting elements.
I tried to make the exercise, and i think I have a good solution O(n). is It a valid solution ?
Is it a better solution that the BEST solution proposed in te lesson ?
Problem: You are given an integer m (1 􏰀 m 􏰀 1 000 000) and two non-empty, zero-indexed arrays A and B of n integers, a0,a1,...,an−1 and b0,b1,...,bn−1 respectively (0 􏰀 ai,bi 􏰀 m). The goal is to check whether there is a swap operation which can be performed on these arrays in such a way that the sum of elements in array A equals the sum of elements in array B after the swap. By swap operation we mean picking one element from array A and
one element from array B and exchanging them.
I tested my solution with these values :
int a[] = {2, 7, 12, 16};
int b[] = {4, 8, 9};
m = 16;
note: I commented the return to see the swapped values.
public int resultat(int[] A, int B[], int max) {
int sumA = Arrays.stream(A).sum();
int sumB = Arrays.stream(B).sum();
int[] countA = count(A, max);
int[] countB = count(B, max);
int diff = sumA - sumB;
int diffMin = 0;
if (diff % 2 != 0) {
return -1;
}
diffMin = diff / 2;
if (sumA > sumB) {
if (diff < countA.length && diffMin < countB.length && countA[diff] != 0 && countB[diffMin] != 0) {
System.out.println("A:" + diff + "- B:" + diffMin);
//return 1;
}
} else {
if (diffMin < countA.length && diff < countB.length && countB[diff] != 0 && countA[diffMin] != 0) {
System.out.println("A:" + diffMin + "- B:" + diff);
//return 1;
}
}
return -1;
}
public int[] count(int[] X, int max) {
int[] p = new int[max + 1];
Arrays.fill(p, 0);
for (int i = 0; i < X.length; i++) {
p[X[i]] += 1;
}
return p;
}
Your solution is O(n + m), because of count(A, max) and count(B, max) invocations. count() is linear.
It's not valid solution. Counter-example: A = [1, 2, 4], B = [3, 5, 1], m = 5. Answer is true, because we can swap 2 with 3. Your code throws ArrayIndexOutOfBoundsException: -2 on countB[diff], because diff is -2. Even if you secure it with, for example diff = Math.abs(sumA - sumB), the algorithm is still not correct and it will return false.
You don't need to do Arrays.fill(p, 0), int default value is 0.
Instead of p[X[i]] += 1 you could write p[X[i]]++.
Here's (i hope) a correct solution.
Please note, that counting can still be put after checking dif is not an odd number to make performance higher.
Note, too, that listA and listB arrays are used as the value at zero place is never used. This is for better understanding, too. We don't need the occurrence of the value 0 but we need the occurrence of max value.
public boolean solution(int[] A, int[] B, int max) {
int[] listA = new int[max+1];
int[] listB = new int[max+1];
int listAsum =0;
int listBsum=0;
for(int i = 0; i<A.length; i++){
listA[A[i]]++;
listAsum +=A[i];
listBsum +=B[i];
}
int diff = listAsum - listBsum;
if(diff%2 == 1) return false;
diff /=2;
for(int i=0; i<A.length; i++){
if((B[i] - diff) >= 0 && (B[i]-diff) <= max && listA[(B[i]-diff)] > 0) return true;
}
return false;
}
public boolean solution(int[] A, int[] B, int max) {
int[] count = new int[max + 1];//count(A, max);
int sum_a = 0; //Arrays.stream(A).sum();
int sum_b = 0;//Arrays.stream(B).sum();
for (int i = 0; i < A.length; i++) {
count[A[i]]++;
sum_a += A[i];
sum_b += B[i];
}
int d = sum_b - sum_a;
if (d % 2 == 1) return false;
d /= 2;
for (int i = 0; i < A.length; i++) {
if ((B[i] - d) >= 0 && (B[i] - d) <= max && count[(B[i] - d)] > 0)
return true;
}
return false;
}
public int[] count(int[] X, int max) {
int[] p = new int[max + 1];
Arrays.fill(p, 0);
for (int i = 0; i < X.length; i++) {
p[X[i]]++;
}
return p;
}

Write function which is return array of prime factors

I have a function it returns prime factors of a number but when I initialize int array I set size.So the result consists unnecessary zeros.How can I return result array without zeros or how can I initialize array applicable size? I am not using Lists
public static int[] encodeNumber(int n){
int i;
int j = 0;
int[] prime_factors = new int[j];
if(n <= 1) return null;
for(i = 2; i <= n; i++){
if(n % i == 0){
n /= i;
prime_factors[j] = i;
i--;
j++;
}
}
return prime_factors;
}
Thanx!!!
Here is a quick way to get about the prime factors problem that I recently worked out. I don't claim it is original, but I did create it on my own. Actually had to do this in C, where I wanted to malloc only once.
public static int[] getPrimeFactors(final int i) {
return getPrimeFactors1(i, 0, 2);
}
private static int[] getPrimeFactors1(int number, final int numberOfFactorsFound, final int startAt) {
if (number <= 1) { return new int[numberOfFactorsFound]; }
if (isPrime(number)) {
final int[] toReturn = new int[numberOfFactorsFound + 1];
toReturn[numberOfFactorsFound] = number;
return toReturn;
}
final int[] toReturn;
int currentFactor = startAt;
final int currentIndex = numberOfFactorsFound;
int numberOfRepeatations = 0;
// we can loop unbounded by the currentFactor, because
// All non prime numbers can be represented as product of primes!
while (!(isPrime(currentFactor) && number % currentFactor == 0)) {
currentFactor += currentFactor == 2 ? 1 : 2;
}
while (number % currentFactor == 0) {
number /= currentFactor;
numberOfRepeatations++;
}
toReturn = getPrimeFactors1(number, currentIndex + numberOfRepeatations, currentFactor + (currentFactor == 2 ? 1 : 2));
while (numberOfRepeatations > 0) {
toReturn[currentIndex + --numberOfRepeatations] = currentFactor;
}
return toReturn;
}
Allocate as many factors as you think the number may have (32 sounds like a good candidate), and then use Arrays.copyOf() to cut off the array at the actual limit:
return Arrays.copyOf(prime_factors, j);

Categories