Question Bank
Numeric Puzzles and FizzBuzz Challenges
Difficulty: Medium
Six numeric warm-ups: recursive exponent, random sampling, prime check, recursive 1..n, completing missing numbers, and iterative Fibonacci.
Numeric Puzzles and FizzBuzz Challenges
Six numeric warm-ups: recursive exponent, random sampling, prime check, recursive 1..n, completing missing numbers, and iterative Fibonacci.
1,152 views
5
Implement exponent(a, n) without using Math.pow or **. Recursion is fine for small n; describe the limit.
Examples
Example 1:
Input: exponent(4, 2), exponent(2, 10)
Output: 16, 1024
Explanation: a^n = a * a^(n-1); base case is n = 0 returning 1.Implement generateRandomItem(arr) that returns a uniformly random element of arr. Make sure no item is more likely than others.
Examples
Example 1:
Input: generateRandomItem(['a', 'b', 'c'])
Output: 'a' | 'b' | 'c' (uniform)
Explanation: `Math.floor(Math.random() * arr.length)` produces a uniform integer in `[0, length - 1]`.Implement isPrime(n) covering 0 and 1, the special case 2, and only checking odd divisors up to sqrt(n).
Examples
Example 1:
Input: isPrime(0), isPrime(2), isPrime(3), isPrime(9), isPrime(17)
Output: false, true, true, false, true
Explanation: Reject 0/1, accept 2, reject other evens, then test odd divisors `i` with `i * i <= n`.Write a recursive count(n) that returns [1, 2, ..., n]. Don't mutate a shared array between calls.
Examples
Example 1:
Input: count(3)
Output: [1, 2, 3]
Explanation: Recursive case: take count(n - 1) and append n. Base case: n === 1 returns [1].Implement completeArray(arr) that returns a sorted array containing every integer between min(arr) and max(arr), filling in the missing numbers.
Examples
Example 1:
Input: completeArray([1, 7, 3, 6]), completeArray([5, 0, -3, 2])
Output: [1, 2, 3, 4, 5, 6, 7], [-3, -2, -1, 0, 1, 2, 3, 4, 5]
Explanation: Compute min/max, iterate from min to max, and emit any integer not already present.Write iterative fibonacci(n) returning the nth number in [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]. Use two variables, not an array.
Examples
Example 1:
Input: fibonacci(5)
Output: 5
Explanation: In this convention `fib(1) = fib(2) = 1`, so the 5th term is `1, 1, 2, 3, 5`.