Katkat

Solve jump maximization and palindromic path queries

UberSoftware Engineer · Online Assessment

Last updated

This problem tests dynamic programming with array constraints and tree-based traversal combined with bitwise parity checks for palindromic properties.

Part 1: Max Jump Score

Given an integer array nums and an integer k, you start at index 0. From index i, you can jump to any index j such that i < j <= i + k. Each index i has an associated score nums[i]. Your goal is to maximize the sum of scores of the indices visited in a path ending at the last index n-1.

Function Signature

def max_jump_score(nums: List[int], k: int) -> int:

Example

Input: nums = [10, -5, 2, 8, 1], k = 2 Output: 19 Explanation: Path is index 0 -> 2 -> 4. Sum = 10 + 2 + 1 = 13. Wait, path 0 -> 1 -> 2 -> 4 is 10-5+2+1 = 8. Path 0 -> 2 -> 3 -> 4 is 10 + 2 + 8 + 1 = 21. Max is 21.

Part 2: Palindromic Ancestor Paths

Given a tree with n nodes (0 to n-1) where each node has a character c, and a list of queries (u, v), determine if the path from node u to node v can be rearranged to form a palindrome. A path can be rearranged into a palindrome if at most one character appears an odd number of times.

Function Signature

def can_form_palindrome(n: int, edges: List[List[int]], chars: str, queries: List[List[int]]) -> List[bool]:

Constraints

  • n <= 10^5
  • k 0 -> 2 has characters 'b', 'a', 'a'. Since 'b' appears once and 'a' twice, it can form a palindrome "aba".

Hints

Hint 1

For Part 1, use a sliding window maximum with a monotonic deque to keep track of the best previous DP states.

Hint 2

For Part 2, represent the character frequencies as a bitmask (where the i-th bit represents the parity of the count of the i-th letter).

Hint 3

In Part 2, use the property that the parity of the path between u and v can be calculated using the XOR sum of path parities from the root to u and the root to v.

Follow-up questions

  • How would you modify the jump problem if you had to visit exactly 'm' nodes?
  • What is the time complexity of the palindromic query if the tree is unbalanced vs. balanced?
  • How would you handle dynamic updates (changing a character at a node) for the palindrome problem?