Longest Arithmetic Sequence Tree Path - Google Top Interview Questions


Problem Statement :


You are given a binary tree root. Return the length of the longest path starting from a node that goes top to bottom where its values form an arithmetic sequence.

An arithmetic sequence is a sequence of numbers where the difference between each consecutive two numbers is the same. For example, [2, 4, 6, 8] is an arithmetic sequence as is [1, 4, 7, 10]. A sequence of length two or fewer is considered an arithmetic sequence.

Constraints

0 ≤ n ≤ 100,000 where n is the number of nodes in root

Example 1

Input

root = [1, [4, [7, [0, null, null], null], null], null]

Output

3



Solution :



title-img




                        Solution in C++ :

int maxS = 0;
void dfs(Tree* root, int diff, int l) {
    maxS = max(maxS, l);
    if (!root) {
        return;
    }
    if (root->left) {
        if (root->left->val - root->val == diff) {
            dfs(root->left, diff, l + 1);
        } else {
            dfs(root->left, root->left->val - root->val, 2);
        }
    }
    if (root->right) {
        if (root->right->val - root->val == diff) {
            dfs(root->right, diff, l + 1);
        } else {
            dfs(root->right, root->right->val - root->val, 2);
        }
    }
}
int solve(Tree* root) {
    if (root) {
        maxS = 1;
    } else {
        return 0;
    }
    dfs(root, 0, 1);
    return maxS;
}
                    


                        Solution in Java :

import java.util.*;

/**
 * public class Tree {
 *   int val;
 *   Tree left;
 *   Tree right;
 * }
 */

class Solution {
    int ans;

    public int solve(Tree root) {
        if (root == null) {
            return 0;
        }

        ans = 1;
        sol(root);
        return ans;
    }

    HashMap<Integer, Integer> sol(Tree root) {
        if (root == null) {
            return new HashMap<>();
        }

        HashMap<Integer, Integer> l = sol(root.left);
        HashMap<Integer, Integer> r = sol(root.right);

        HashMap<Integer, Integer> mp = new HashMap<>();

        if (root.left != null) {
            int ldiff = root.val - root.left.val;
            int x = l.getOrDefault(ldiff, 1);
            int y = mp.getOrDefault(ldiff, 1);
            mp.put(ldiff, Math.max(x + 1, y));
            ans = Math.max(ans, mp.get(ldiff));
        }

        if (root.right != null) {
            int rdiff = root.val - root.right.val;
            int x = r.getOrDefault(rdiff, 1);
            int y = mp.getOrDefault(rdiff, 1);
            mp.put(rdiff, Math.max(x + 1, y));
            ans = Math.max(ans, mp.get(rdiff));
        }

        return mp;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    # global ans to use same solve function for recursion 😅
    ans = 0
    # diff is diffrence of cur value with prev to check airth seq
    # ltill is longest airth seq ending before cur node
    def solve(self, cur, ltill=0, diff=None):
        # Intialize a global ans ans is max of prev longest airthmetic seq and cur longest
        self.ans = max(self.ans, ltill)
        # Check if ther is left child
        if cur.left:
            # compute diff with left child
            ldiff = cur.left.val - cur.val
            self.solve(
                cur.left,
                # if diff with previous child is diffrent
                # from diff of cur from par
                # or it's root new airthmetic sequence
                # start from here so ltill is 1
                # else extend prev max length ltill by 1
                1 if diff == None or ldiff != diff else ltill + 1,
                ldiff,
            )
        # same for right
        if cur.right:
            rdiff = cur.right.val - cur.val
            self.solve(cur.right, 1 if diff == None or rdiff != diff else ltill + 1, rdiff)

        # we start count from 0 so +1 solve single legth seq also
        return self.ans + 1
                    


View More Similar Problems

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →