Leetcode question to finding the longest univalue path [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Question:
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
source
A solution to this is:
class Solution
{
public:
int max_len = INT_MIN;
int longestUnivaluePath(TreeNode* root)
{
if(!root)
return 0;
helper(root, root->val);
return max_len;
}
int helper(TreeNode* root, int prev_value)
{
if(!root)
return 0;
int left = helper(root->left, root->val);
int right = helper(root->right, root->val);
max_len = std::max(left + right, max_len); // Why do we do this? I have no idea
if(root->val == prev_value)
return std::max(left, right) + 1;
return 0;
}
};
Why do we do this: max_len = std::max(left + right, max_len); This part does not make sense to me. If anyone can actually explain it simply I would greatly appreciate the insight.

The longest path doesn't have to be strictly descending, right? For example, the length of the longest univalue path in the following tree is 2:
3
/ \
3 3
In their algorithm,
left is the length of the longest descending univalue path down the left branch of node.
right is the length of the longest descending univalue path down the right branch of node.
Combined, left + right is the length of the longest univalue path going through the node node, which is the new candidate path.
So the line in question actually means
max_len = std::max(candidate_len, max_len);
which is a canonical running max algorithm: it processes the candidate values sequentially, one by one, and keeps the maximum value seen thus far in max_len. Eventually, max_len will end up with the maximum value of all candidates.

Related

How to optimise this code of sorting,this is not exeuting within the time limits.This question is from hackerrank [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How to reduce the time compexity of this code,this is not exeuting within the time
exact ques from hackerrank--
Complete the circularArrayRotation function in the editor below. It should return an array of integers representing the values at the specified indices.
circularArrayRotation has the following parameter(s):
a: an array of integers to rotate
k: an integer, the rotation count
queries: an array of integers, the indices to report
vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
int i,temp;
vector<int> ans;
//to perform number of queries k
while(k--)
{ //shift last element to first pos and then move rest of elements to 1 postion forward
temp=a[a.size()-1]; //last element
for(i=a.size()-1;i>0;i--)
{
a[i]=a[i-1];
}
a[0]=temp;
}
for(i=0;i<queries.size();i++)
{
ans.push_back(a[queries[i]]);
}
return ans;
}
The vector a is being rotated by k in the while loop. The whole loop can be removed by adding k and using modulo when accessing elements in a:
ans.push_back(a[(queries[i]+k)%a.size()]);
Note: you might need handling of negative values of k.
Note: Maybe it should be minus instead of plus.
An alternative could be to use std::rotate.
Furthermore, the ans vector should be pre-allocated to reduce the number of allocations to one:
ans.reserve(queries.size());

What is the median value is decimal? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm writing a program to find the median of an array in CPP. I am not sure if I have a clear idea about what a median is. As far as I know, I've written my program to find median but when the array is even-numbered, I'm confused whether I should print the ceiling or ground value of division ofthe decimal output I get when I divide the middle two elements from the array.
using namespace std;
void findMedian(int sortedArray[], int N);
int main()
{
int ip[4] = {1, 2, 5, 8};
findMedian(ip, 4);
}
void findMedian(int sortedArray[], int N)
{
int size = N;
int median;
if ((size % 2) != 0)
{
median = sortedArray[(size / 2)];
}
else
{
median = (sortedArray[(size / 2) - 1] + sortedArray[size / 2]) / 2;
}
cout << median;
}
Thanks in advance, also if anyone can give the literal purpose of finding a median, I'd appreciate and it'd help me not ask this question again when I have to deal with Median.
Pardon my English.
on odd array the median is unique, but in a even array there are two medians: the lower median (the one in (n/2)th position) and the upper median (the one in (n/2+1) th position). I usually always see that the lower median is used as "median" for even arrays.
In this case you need only one formula for even and odd arrays:
medianPosition = n/2; // integer division
median = sortedArray[medianPosition];
Note that it is true only for array where indices starts with zero (like C/C++).

Middle node of Singly linked List [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I found this code to print the middle node of a list in C++ but I don't understand the code...Someone can explain me this?
Type& findMiddleNode()
{
int check = 0;
nodeType *current;
nodeType *mid;
current = first;
mid = first;
while (current != NULL)
{
current = current->link;
check = (check + 1) % 2;
if (check == 0)
mid = mid->link;
}
return mid->info;
}
PD: This code works perfect, but I dont understand! Someone help me to understand this. Thanks!
The basic idea is to move two pointers B and A through the list, but with B moving at only half the speed of A.
The statement
check = (check + 1) % 2;
… gives check the values 0, 1, 0, 1 and so on, which is used to move B only every second time A is moved.
The same idea is one possible (and expected) answer to a question about checking whether a singly linked list contains a loop. In this case the fast moving pointer will catch up with the slow one after both have entered the loop.
A simpler way to do the same, with just about the same work expended by the program, is to (1) count the number of nodes n, and (2) starting at the start again, go to node number n/2.
Step (1) moves a pointer n times, like A above, and step (2) moves a pointer n/2 times, like B above.

Array Best Match [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
You have been called upon to write a Match-Making program for a marriage beaureau. The beaureau’s questionnaire has 8 statements, and the applicant indicates her or his degree of agreement on a scale of 1 to 5. The response of the applicant is entered through the keyboard. Each response contains the applicant’s code number, sex (F or M), & response to the questionnaire (8 integers).
You may assume that there are no more than 50 applicants. Your program should match each person with 3 most compatible person of opposite sex and should print the code no. of applicant along with code no. of prospective applicants.
i want to implement this through c++. Is there any matching algorithm for this ?. or there is some simple approach. It would be nice for me, if you write the whole function.
and sorry, if the question is very simple bcs i'm a learner.
Based on our comments above I'll post some comments to get you started. But remember the best thing is to try something on your own and then get help afterwards...
int questionnaire_answers[50][8]; // 2D array holding answers
int sex[50]; // 1D array holding sex of those who answered
int i, j;
int index = 0;
int best = 999999;
int distance;
// We look for the best match for the first person
for (i = 1; i < 50; i++)
{
if (sex[0] != sex[i])
{
// Calculate the distance from index 0 to index i
// See note below
distance = 0;
for (j=0 ; j < 8; j++)
{
distance = distance + abs(questionnaire_answers[0][j]-questionnaire_answers[i][j]);
}
}
else
{
distance = 999999;
}
if (distance < best)
{
best = distance;
index = i;
}
}
// Now index holds the index of the best match
I'll leave it to you to figure out how to find the second and third best match :)
IMPORTANT:
I have used a simple linear distance calculation. In the real world you will probably do better with something more complicated. The world of math has several good option, e.g. least/minimum-mean-square
Have fun!
You can use Cosine Correlation. First normalize the 50X8 matrix such that each column has mean=0 and standard deviation=1. Now for each record(row), calculate the cosine correlation with every other record. The record giving maximum cosine correlation will be a match for this record.

Backtrack in any programming language [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I was given a task of writing a program for string permutation. I understand the logic, but not the exact meaning of the Backtrack in this program. Please explain the for-loop functionality, when swap will be called, when permutate() will be called, and the exact meaning of backtrack.
# include <stdio.h>
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
getchar();
return 0;
}
Sketching the call stack can help you understanding how the algorithm works. The example string "ABC" is a good starting point. Basically, this is what will happen with ABC:
permute(ABC, 0, 2)
i = 0
j = 0
permute(ABC, 1, 2)
i = 1
j = 1
permute(ABC, 2, 2)
print "ABC"
j = 2
string = ACB
permute(ACB, 2, 2)
print "ACB"
string = ABC
j = 1
string = BAC
permute(BAC, 1, 2)
.... (everything starts over)
As usual, in the example above, indentation defines what happens inside each of the recursive calls.
The reasoning behind the for loop is that every permutation of string ABC is given by ABC, BAC and CBA, plus every permutation of the substrings BC, AC and BA (remove the first letter from each of the previous ones). For any string S, the possible permutations are obtained by swapping every position with the first one, plus all of the permutations of each of these strings. Think of it like this: any permuted string must start with one of the letters in the original string, so you place every possible letter in the first position, and recursively apply the same method to the rest of the string (without the first letter).
That's what the loop is doing: we scan the string from the current starting point (which is i) up to the end, and at each step we swap that position with the starting point, recursively call permute() to print every permutation of this new string, and after that we restore the string back to its previous state, so that we have the original string to repeat the same process with the next position.
Personally, I don't like that comment saying "backtrack". A better term would be "winding back", because at that point the recursion winds back and you prepare your string for the next recursive call. Backtrack is normally used for a situation in which you explored a subtree and you didn't find a solution, so you go back up (backtrack) and try a different branch. Taken from wikipedia:
Backtracking is a general algorithm for finding all (or some)
solutions to some computational problem, that incrementally builds
candidates to the solutions, and abandons each partial candidate c
("backtracks") as soon as it determines that c cannot possibly be
completed to a valid solution.
Note that this algorithm does not generate the set of permutations, because it can print the same string more than once when there are repeated letters. An extreme case is when you apply it to the string "aaaaa", or any other string with one unique letter.
"Backtracking" means, you are gong back one step in your solution space (think of it as a decision tree and you are going up one level). It is usually used if you can rule out certain sub-trees in the decision space, and gives significant performance boost compared to full exploration of the decision tree if and only if it is very likely that you can rule out larger parts of the solution space.
You can find an exhaustive expalnation of a similar algorithm here: Using recursion and backtracking to generate all possible combinations