Indeed Interview Question for SDE-2s


Country: United States




Comment hidden because of low score. Click to expand.
0
of 0 vote

/* Function to find LCA of n1 and n2. The function assumes that both 
   n1 and n2 are present in BST */
struct node *lca(struct node* root, int n1, int n2) 
{ 
    if (root == NULL) return NULL; 
  
    // If both n1 and n2 are smaller than root, then LCA lies in left 
    if (root->data > n1 && root->data > n2) 
        return lca(root->left, n1, n2); 
  
    // If both n1 and n2 are greater than root, then LCA lies in right 
    if (root->data < n1 && root->data < n2) 
        return lca(root->right, n1, n2); 
  
    return root; 
}

- Nits August 16, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

You are assuming its a Binary search tree.

- Abhs June 22, 2022 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

(let i and j be the given nodes)

- reverse the graph
- perform a BFS from 'i' keeping track of the layer/level where the other nodes are discovered (let Ki denote the distance of node K from i)
- perform a similar BFS from 'j', collecting Kj for every node K in the graoh

at this point, the shortest distance (in hops) from every node to nodes 'i' and 'j' is known

min(abs(Ki - Kj)) for every node K will give the K that is the least common ancestor

- anon November 25, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More