PE2 (AY18/19)
Last updated
Last updated
Questions:
Official Answers:
This question is a give-away question, the most important part is that m2[j][i] = m1[i][j]
.
A problem that uses technique.
Notice that this recursive solution cannot pass two cases since it will cause a stack overflow.
This iterative can pass all the test cases and it uses the sliding window technique to move the boundaries.
An awesome variant question of Binary Search
Instead of using the method in the comments, I used the idea of mapping. Before that, since we already know Binary Search needs the list to be sorted. In this question, the list is sorted but in a another way -- "rotated". For example, in the list below, the actual input position is shown in red, while the sorted position should be in blue.
The way to treat the list as sorted is to use the idea of offset. We still search from the middle, but the actual middle is not the red 3, but the blue 3. Suppose we want to search for number 4 (pos 6), we compare it with the actual middle number, which is 1 in pos 0(not 4 in pos 3). Then we find it is bigger, so we can be sure number 4 is at right of actual middle number 1.
One thing we can notice is that the offset is related to how many bits we have right rotated. The logic is below:
After knowing this, we can modify our Binary Search slightly to pass this question
The idea given in the comments are pretty awesome! That is to combine the is_prime
and is_semiprime
together. This is done by if i
is a factor of n
and i
is a prime, then if n/i
is also a prime, then n
is a semiprime.
An awesome and hard problem about bracket matching. It is obvious to use stack to solve it. But here recursion is required, making it harder to think.
Instead of using the sliding window technique in 2. Palindrome, we mimic the idea of using stack to solve this problem, that is whether the "bracket" is consumed or not. Thus, the recursive function will return the index of the first unconsumed character.
The first two return blocks both returns the position that cannot be consumed. The Line 10 will return the solution for the subproblem, which is the string begins from end+1
. The Line 12 will return the begin position if it cannot be consumed in the current function call.
The tricky point is that in Line 8, you try to consume open bracket in the current function call.
The call in main()
should be
Include the is_prime()
and count_factors()
into the cheatsheet
A question that combines the is_prime()
in , and the way to count all the prime factors of a num in .