Split First N Squares

Easy
0/40
Average time to solve is 20m
profile
Contributed by
3 upvotes
Asked in company
Adobe

Problem statement

You are given an integer 'N'. Your task is to split the set of first 'N' squares into two sets such that the difference of their sum is minimized. It is guaranteed that 'N' is always a multiple of eight.

Each square must belong to one and exactly one set. Return a binary string of length 'N', if the ‘i’th character of the string is ‘0’ then ‘i’ * ‘i’ is in Set1 else in Set2.

For example:
N = 8, Set of first 8 squares = [1, 4, 9, 16, 25, 36, 49, 64]

Set1 = [1, 16, 36, 49], Set2 = [64, 25, 9, 4]

Here difference is (64 + 25 + 9 + 4) - (1 + 16 + 36 + 49 ) = 0 and = "01101001"
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer 'T' denoting the number of test cases to run. Then the test case follows.

The first line of each test case contains an integer 'N'. 
Output Format:
For each test case return a binary string of length 'N',   if the ‘i’th character of the string is ‘0’ then ‘i’ * ‘i’ is in Set1 else in Set2. 

Output for each test case is printed in a separate line.
Note:
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 5000   

N is always a multiple of 8. 

Time Limit: 1 sec
Sample Input 1:
2
8 
16
Sample Output 1:
10010110
0101001111111000
Explanation For Sample Output 1:
for the first test case, Set1 = [1, 16, 36, 49], Set2 = [64, 25, 9, 4]
10010110 and 01101001 both are valid. 

For the second test case, the minimum difference is 0. 
Sample Input 2:
2
24
32
Sample Output 2:
101011111111111111100000
10010110100101101001011010010110
Hint

We can always split 8 consecutive squares into two groups such that the difference of their sum is 0.

Approaches (1)
Observation

We can observe that,

n^2 - (n+1)^2 - (n+2)^2 +(n+3)^2 -(n+4)^2 +(n+5)^2 +(n+6)^2 -(n+7)^2 = 0

 

As a result, we will keep taking 8 consecutive numbers from the beginning and split them into two sets. Such that their difference is 0. So in the end, our overall difference will be 0.

The algorithm will be-

  1. cnt = n / 8
  2. ans = ['10010110'] for size cnt.
  3. Return concatenation of all the strings in ans.

  

Time Complexity

O(N), where ‘N’ is the given integer. 

 

Since we are forming a string of length ‘N’ by iterating over it once.

Space Complexity

O(N), where 'N' is the given integer

 

The space complexity due to the final string will be O(n).

Code Solution
(100% EXP penalty)
Split First N Squares
Full screen
Console