Data Structures & AlgorithmsHardGATE CS · ICPC regional
Consider this function:
Consider this function:
def g(n):
if n < 2:
return n
if n % 2 == 0:
return g(n - 3) + g(n - 3)
return g(n - 3) - 1What value does g(10) return?- A. 3
- B. 0
- C. 2
- D. 4
Correct answer: C. 2
Evaluate by recursion: the even branch adds two calls and the odd branch subtracts 1, which gives 2. Swapping the parity test gives -1, subtracting instead of adding gives 0, and dropping the −1 gives 4.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Starting from the integer 14, one operation either adds 1, subtracts 1, or doubles the current value. Values may be any non-negative…
- An undirected graph has the vertices A, H, I, M, R, U, Y, Z and the edges M–Y, M–Z, M–I, M–U, M–H, A–U, A–H, R–Z, R–H, Y–Z, Y–I, Z–I, Z–H…
- A tree has the vertices A, D, F, H, I, K, R, S, X, Z and the edges A–R, R–S, R–X, R–I, X–K, A–H, X–F, S–Z, A–D. What is the minimum number…
- On an 7×7 chessboard, rows and columns are numbered 0 to 6, and squares are written (row, column). A knight moves in the usual L-shape…
- A tree has vertices with weights in brackets: U[11], E[3], J[12], L[9], K[11], B[6], G[1]. The edges are U–E, E–J, J–L, J–K, U–B, J–G. A…
- An undirected graph has the vertices F, H, I, K, N, U and the edges U–K, U–H, F–K, F–N, I–H, K–H. In how many ways can each vertex be…