Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,152,482 members, 7,816,141 topics. Date: Friday, 03 May 2024 at 06:25 AM

Can You Solve This Google Coding Interview Problem? (pics) - Programming (2) - Nairaland

Nairaland Forum / Science/Technology / Programming / Can You Solve This Google Coding Interview Problem? (pics) (3182 Views)

Please How Did You Solve Your Power Need Without Use Of Generator / I Have A Google Coding Interview Coming Up. I’m Panicking!!! / Turing.com Live Coding Interview Preparation (2) (3) (4)

(1) (2) (3) (4) (5) (Reply) (Go Down)

Re: Can You Solve This Google Coding Interview Problem? (pics) by truthCoder: 11:34am On Dec 21, 2022
TastyFriedPussy:
A board has got a painted tree graph, consisting of n nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles.

Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer.

A bad boy Vasya came up to the board and wrote number sv near each node v — the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board.

Your task is to restore the original tree by the node colors and numbers sv.

Input
The first line of the input contains a single integer n (2 ≤ n ≤ 105) — the number of nodes in the tree. Next n lines contain pairs of space-separated integers ci, si (0 ≤ ci ≤ 1, 0 ≤ si ≤ 109), where ci stands for the color of the i-th vertex (0 is for white, 1 is for black), and si represents the sum of values of the edges that are incident to the i-th vertex of the tree that is painted on the board.

Output
Print the description of n - 1 edges of the tree graph. Each description is a group of three integers vi, ui, wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 0 ≤ wi ≤ 109), where vi and ui — are the numbers of the nodes that are connected by the i-th edge, and wi is its value. Note that the following condition must fulfill cvi ≠ cui.

It is guaranteed that for any input data there exists at least one graph that meets these data. If there are multiple solutions, print any of them. You are allowed to print the edges in any order. As you print the numbers, separate them with spaces.


Sample input
3
1 3
1 2
0 5
Sample output

3 1 3
3 2 2

Sample input
6
1 0
0 3
1 8
0 2
0 3
0 0

Sample output
2 3 3
5 3 3
4 3 2
1 6 0
2 1 0


To solve this problem, you can iterate over the nodes and use the node colors and values to reconstruct the tree. Here's a rough outline of a possible solution:

Start with an empty list of edges.
Iterate over the nodes, starting from the first one. For each node, do the following:
If the current node is white, find the next black node in the list and create an edge between the two nodes with a value equal to the difference between their sv values.
If the current node is black, find the next white node in the list and create an edge between the two nodes with a value equal to the difference between their sv values.
Repeat this process until you have processed all the nodes.


function restoreTree(n: number, nodes: Array< [number, number] > ) : Array < [number, number, number] > {
const edges: Array<[number, number, number]> = [];
for (let i = 0; i < n; i++) {
const [ci, si] = nodes[i];
let j = i + 1;
while (j < n && nodes[j][0] === ci) {
j++;
}
if (j < n) {
const [cj, sj] = nodes[j];
edges.push([i + 1, j + 1, Math.abs(si - sj)]);
}
}
return edges;
}


Courtesy, ChatGPT.

2 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by Nobody: 11:43am On Dec 21, 2022
sqlPAIN:
Rubbish.... Everything is not front-end and back-end......
..


If not for frontend and backend u won't be here on Nairaland typing trash and posting copied solution's grin

5 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by truthCoder: 11:46am On Dec 21, 2022
is coding all about data structures and algorithms

Coding involves many different aspects, and data structures and algorithms are just one part of it. In general, coding involves designing, writing, testing, and debugging code to solve problems or accomplish specific goals.

Data structures and algorithms are important tools that are used to solve problems and perform tasks in an efficient and effective way. They allow you to organize and manipulate data in a way that is optimized for a particular purpose, such as searching, sorting, or storing data.

However, there is much more to coding than just data structures and algorithms. Other important aspects of coding include:

Designing and planning: This involves understanding the problem or goal, determining the requirements and constraints, and designing a solution that meets those requirements.
Writing code: This involves writing the actual code that implements the solution, using a programming language and following best practices for code organization, readability, and maintainability.
Testing and debugging: This involves testing the code to ensure that it works correctly, and debugging any issues that arise.
Collaborating and communicating: This involves working with other developers and stakeholders, such as project managers and users, to ensure that the solution meets their needs and meets project goals.
Overall, coding involves a wide range of skills and activities, and data structures and algorithms are just one part of the picture.

4 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by Nobody: 11:51am On Dec 21, 2022
sqlPAIN:
I can't just wait for when chatGpt would get creative enough to start weeding you all out.
Nonsense

It will weed u out first.

You're the worst of the worst.


U didn't even attempt the question in order to learn from your mistake assuming u got it wrong so you'd try again.

U didn't even rename some variables or change some patterns so your cheat will be difficult to spot.
U pasted everything verbatim.


In your attempt to prove to everyone that your C++ or whatever Grandpa language you're learning is superior u went ahead to copy everything word for word.... Copying, the worst form of cheating is what u indulge in.


You're the quackest of all the quack programmers.... worst of all u still have a loud mouth.

ChatGPT will even spit on u b4 weeding u out.

8 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by truthCoder: 12:04pm On Dec 21, 2022
Wow, it's really impressive how there are all these self-proclaimed geniuses out there who think they're the best because they can answer some trivia questions about data structures and algorithms. Newsflash: that doesn't mean you're actually a good coder. In fact, most of these DSA-obsessed babies don't have a single practical project to their name. They've never solved a real-life dev problem, let alone achieved 100 MAU on anything. And yet, they have the audacity to beg for hand-me-down laptops and criticize others who can afford brand new desk set-ups.

But hey, it's not like being a good coder is about being able to think on your feet and adapt your current knowledge to solve real problems. Oh wait, that's exactly what it's about. That's why teams are made up of different people with different skills, not just the CTO. But I'm sure these yapping puppies know better than that. Carry on, guys

4 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by airsaylongcome: 12:07pm On Dec 21, 2022
Lol! Nice one @GreatIgboman. Something was so damn off with a younging rushing out with a solution. And doing so in C++.

Valid points though about the need to have more posts and engagements about DSA. Not just talking about it , but more hardcore stuff.

Anyway for me TastyFriedWhatever is the same person as sqlPAIN.

9 Likes 1 Share

Re: Can You Solve This Google Coding Interview Problem? (pics) by Nobody: 12:08pm On Dec 21, 2022
airsaylongcome:
Lol! Nice one @GreatIgboman. Something was so damn off with a younging rushing out with a solution. And sound so in C++.

Valid points though about the need to have more posts and engagements about DSA. Not just talking about it , but more hardcore stuff.

Anyway for me TastyFriedWhatever is the same person as sqlPAIN.

I swear 100%.

2 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by Nobody: 12:12pm On Dec 21, 2022
airsaylongcome:
Lol! Nice one @GreatIgboman. Something was so damn off with a younging rushing out with a solution. And sound so in C++.

Valid points though about the need to have more posts and engagements about DSA. Not just talking about it , but more hardcore stuff.

Anyway for me TastyFriedWhatever is the same person as sqlPAIN.

There's no single Algo question that have been posted on Nl without a valid unique solution lol.

trust me... I believe I've searched for them all (the majority of them)... even during the time when dhtml was active here... far back as 10+ years ago.

This question this person is calling ordinary isn't ordinary but difficult.

To solve it u need to leave wateva youre doing and focus on itt.... even if uv been solving algo questions consistently.



People don't just engage with algo post, that's the reality... if u wan to learn algorithms... they're many websites and forum for that.
Re: Can You Solve This Google Coding Interview Problem? (pics) by Nobody: 12:22pm On Dec 21, 2022
sqlPAIN

I dare u to explain your solution line by line.


chances are, u don't even understand what you've pasted. grin

5 Likes 1 Share

Re: Can You Solve This Google Coding Interview Problem? (pics) by truthCoder: 12:26pm On Dec 21, 2022
GREATIGBOMAN:
sqlPAIN

I dare u to explain your solution line by line.


chances are, u don't even understand what you've pasted. grin

grin

1 Like

Re: Can You Solve This Google Coding Interview Problem? (pics) by sqlPAIN: 12:33pm On Dec 21, 2022
GREATIGBOMAN:
sqlPAIN

I dare u to explain your solution line by line.


chances are, u don't even understand what you've pasted. grin
Even if I did, you'd not be smart enough to understand....so stick to react JS and co
Re: Can You Solve This Google Coding Interview Problem? (pics) by Nobody: 12:50pm On Dec 21, 2022
sqlPAIN:

Even if I did, you'd not be smart enough to understand....so stick to react JS and co


U can't, because there's no place online to copy the explanation.

I'm very sure you're not older than 20years of age grin
Re: Can You Solve This Google Coding Interview Problem? (pics) by qtguru(m): 12:57pm On Dec 21, 2022
GREATIGBOMAN:



U can't, because there no place online to copy the explanation.

I'm very sure you're not older than 20years of age grin


That will explain alot

1 Like

Re: Can You Solve This Google Coding Interview Problem? (pics) by OlawaleBammie: 1:09pm On Dec 21, 2022
sqlPAIN:
mehn shut ur trap and go and sit down... You can't solve it be say you can solve it, rubbish. this is light years out of your league, you're not a real programmer, your just an ordinary web dev,period!!!so Bleep of and go continue with react,vue, CSS and the likes.... Learning hello world? Lolzzz
and u tink u re making sense??

Funny you.

1 Like

Re: Can You Solve This Google Coding Interview Problem? (pics) by OlawaleBammie: 1:14pm On Dec 21, 2022
Kaycee54321:


I'm just saying 'cause of the nature of his outbursts.
A bloke that keeps saying stuff like 'you're just a mere web developer' to strangers online should at least, have some financial muscle to back up the unnecessary conceit...

I don't know why I never see stuff like this on Quora or Discord...just among my fellow black brethren...
it's in their DNA

When dey know small thing, they start to dey misbehave

People like them hate it when u know as much as they know, the always want to be regarded as bozz, they don't want competition, the moment the realize u re on the right way they start exhibiting hatred.

1 Like 1 Share

Re: Can You Solve This Google Coding Interview Problem? (pics) by OlawaleBammie: 1:15pm On Dec 21, 2022
sqlPAIN:
Rubbish....... Simple tree problem they can't solve...If it's to be talking about react, vue,svelte, front-end and back-end,flex box,grid, django and all those fancy rubbishes, that's where you'll see all of them, claiming "tech guru's in the house"..Rubbish. But when it's time for real sh*t, they'll all vanish.. Ordinary websites all of you are developing, small thing you're shouting I'm In tech, I'm in tech. What tech. You think web dev is technology? Rubbish.....
are u done??
Re: Can You Solve This Google Coding Interview Problem? (pics) by SavageBoy: 1:46pm On Dec 21, 2022
Fact: Nobody get mouth like Greatigboman for here. The guy just dey give me joygrin

When I saw the rubbish post, I just knew it was that tasty-fried-idiot. Like what someone once told him here, na yahoo you go later use your Laptop do.

4 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by spartan117(m): 2:26pm On Dec 21, 2022
Lol this thread is pure comedy GREATIGBOMAN be calming down small grin

sqlpain aka tastyfried hope you have learnt your lesson?
Go and sin no more
Re: Can You Solve This Google Coding Interview Problem? (pics) by airsaylongcome: 2:30pm On Dec 21, 2022
SavageBoy:
Fact: Nobody get mouth like Greatigboman for here. The guy just dey give me joygrin

When I saw the rubbish post, I just knew it was that tasty-fried-idiot. Like what someone once told him here, na yahoo you go later use your Laptop do.


Na still GIM tell am say na yahoo hin go use that laptop do las las

2 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by Maxxim: 3:22pm On Dec 21, 2022
spartan117:
Lol this thread is pure comedy GREATIGBOMAN be calming down small grin

sqlpain aka tastyfried hope you have learnt your lesson?
Go and sin no more
cheesy
Re: Can You Solve This Google Coding Interview Problem? (pics) by SavageBoy: 4:11pm On Dec 21, 2022
airsaylongcome:


Na still GIM tell am say na yahoo hin go use that laptop do las las

Lol. With this his toxic and negative attitude, even if he abandons programming for yahoo, he wont still succeed.

He's busy calling out people that are doing better than him. None of the persons he called out has ever blamed or cursed their father.

Do you even expect someone that can call out his father in a public forum like this to be sensible and successful in life?

He claim he is not doing programming for the money, yet he's creating a thread on how demotivating learning programming can be without money.

Tastyfried idiot or whatever they call you. Programming is not for you. Better sell that your laptop and use the money to search for a solution to your problem.

1 Like

Re: Can You Solve This Google Coding Interview Problem? (pics) by niel63(m): 4:13pm On Dec 21, 2022
I am a Web Dev who likes React, Vue, Svelte and those small small UI toolkits that makes web dev look like telling a story. grin And you know what, I like am die.

I am in agreement that I know nothing but I hope you know its just a matter of me deciding to pick pick up another language if I feel the need to... as I am currently trying to choose between golang and rust right now grin

And I promise to drop all these in a heartbeat the moment I find something even more lucrative and enriching than this... you know why? Na money I dey find.

If you like wipe head for wall like 55 times, e no go still change the fact say everything dey for us to learn.

I am no pro programmer doing some tricky DSA stuffs like that small 12years old boy wey like to talk about IBM Watson and AI like say na him papa do am.

Being happy is a gift and you choose your path. Some people do not know basic html structure and they are in tech making big money.

So, tech isn't about being bitter about others... rather, it's about solving problems in real life even if it's just creating a shopping cart.

You're so good, yet you let someone else create ChatGPT. You're a mumu boy!!!

4 Likes

Re: Can You Solve This Google Coding Interview Problem? (pics) by namikaze: 4:18pm On Dec 21, 2022
@sqlPAIN
I haven't been online for the past few days and I usually don't even check the programming section because it's usually dry. I'll try solving this today

1 Like

Re: Can You Solve This Google Coding Interview Problem? (pics) by airsaylongcome: 4:21pm On Dec 21, 2022
SavageBoy:


Lol. With this his toxic and negative attitude, even if he abandons programming for yahoo, he wont still succeed.

He's busy calling out people that are doing better than him. None of the persons he called out has ever blamed or cursed their father.

Do you even expect someone that can call out his father in a public forum like this to be sensible and successful in life?

He claim he is not doing programming for the money, yet he's creating a thread on how demotivating learning programming can be without money.

Tastyfried idiot or whatever they call you. Programming is not for you. Better sell that your laptop and use the money to search for a solution to your problem.

I just see him as a troll that enjoys getting a lot of mentions for “going against the grain”. Never take him or his alt seriously. Empty barrels they say….(you know the rest)

1 Like

Re: Can You Solve This Google Coding Interview Problem? (pics) by Nobody: 4:38pm On Dec 21, 2022
niel63:
I am a Web Dev who likes React, Vue, Svelte and those small small UI toolkits that makes web dev look like telling a story. grin And you know what, I like am die.

I am in agreement that I know nothing but I hope you know its just a matter of me deciding to pick pick up another language if I feel the need to... as I am currently trying to choose between golang and rust right now grin

And I promise to drop all these in a heartbeat the moment I find something even more lucrative and enriching than this... you know why? Na money I dey find.

If you like wipe head for wall like 55 times, e no go still change the fact say everything dey for us to learn.

I am no pro programmer doing some tricky DSA stuffs like that small 12years old boy wey like to talk about IBM Watson and AI like say na him papa do am.

Being happy is a gift and you choose your path. Some people do not know basic html structure and they are in tech making big money.

So, tech isn't about being bitter about others... rather, it's about solving problems in real life even if it's just creating a shopping cart.

You're so good, yet you let someone else create ChatGPT. You're a mumu boy!!!
Re: Can You Solve This Google Coding Interview Problem? (pics) by jbreezy: 8:41pm On Dec 21, 2022
Lol…this section ehn
Re: Can You Solve This Google Coding Interview Problem? (pics) by chiedozie198100: 11:57pm On Dec 21, 2022
Re: Can You Solve This Google Coding Interview Problem? (pics) by namikaze: 9:19am On Dec 22, 2022
much harder than I imagined, I've been able to come up with a solution though, let me clean it up.
hopefully it passes all test cases

1 Like 1 Share

Re: Can You Solve This Google Coding Interview Problem? (pics) by namikaze: 10:16am On Dec 22, 2022

class Node:
def __init__(self, id, col, val):
self.id = id
self.color = col
self.value = val

def __str__(self):
return f"id: {self.id}, color: {self.color}, value: {self.value}"


class Result:
def __init__(self, n1, n2, w):
self.startnode = n1
self.endnode = n2
self.weight = w

def __str__(self):
return f"sn: {self.startnode.id}, en: {self.endnode.id}, weight: {self.weight}"


def read_inputs():
n = int(input())
res = set()
for i in range(1, n + 1):
s = input().split()
res.add(Node(i, int(s[0]), int(s[1])))
return res

def solve(nodes):
res = []
while len(nodes) != 0:
maxn = max(nodes, key=lambda v: v.value)
# check stray nodes
if maxn.value == 0:
resolve_res = [next_valid_node(maxn, res)]
else:
resolve_res = resolve_edges(maxn, nodes)
nodes.remove(maxn)
res.extend(resolve_res)
return res

def resolve_edges(maxn, nodes):
res = []
while True:
minn = pick_min(maxn, nodes)
if minn is None:
break
if maxn.value >= minn.value:
res.append(Result(maxn, minn, minn.value))
maxn.value -= minn.value
nodes.remove(minn)
else:
res.append(Result(maxn, minn, maxn.value))
minn.value -= maxn.value
nodes.add(maxn)
break
return res

def pick_min(maxn, nodes):
minn = Node(-1, -1, 999)
for node in nodes:
# check colors, reject same color nodes
if node.color == maxn.color:
continue
if node.value < minn.value:
minn = node
return minn if minn.value != 999 else None

def next_valid_node(strayn, nodes):
straycol = strayn.color
for node in nodes:
startcol, endcol = node.startnode.color, node.endnode.color
if startcol != straycol:
return Result(strayn, node.startnode, strayn.value)
if endcol != straycol:
return Result(strayn, node.startnode, strayn.value)

def main():
nodes = read_inputs()
nodes_test = {
Node(1,1,0),Node(2,0,3),Node(3,1,8 ),
Node(4,0,2),Node(5,0,3),Node(6,0,0)
}
nodes_test2 = {
Node(1,1,3),Node(2,1,2),Node(3,0,5)
}
res = solve(nodes)
[print(r.startnode.id, r.endnode.id, r.weight) for r in res]

if __name__ == "__main__":
main()

1 Like

Re: Can You Solve This Google Coding Interview Problem? (pics) by namikaze: 10:22am On Dec 22, 2022
replace nodes with either nodes_test or nodes_test2 in
res = solve(nodes)
to test with the sample data.
Re: Can You Solve This Google Coding Interview Problem? (pics) by namikaze: 10:29am On Dec 22, 2022
The approach is;
pick the node with the max sv value, either white or black, and then distribute value (by substracting from the sv) to the smallest nodes of the opposite color untill sv becomes zero or the smallest opposite color node is bigger, then repeat with the next max sv node, nodes visited are not reused. this should work for valid inputs

1 Like

Re: Can You Solve This Google Coding Interview Problem? (pics) by Nobody: 5:01pm On Dec 22, 2022
namikaze:
The approach is;
pick the node with the max sv value, either white or black, and then distribute value (by substracting from the sv) to the smallest nodes of the opposite color untill sv becomes zero or the smallest opposite color node is bigger, then repeat with the next max sv node, nodes visited are not reused. this should work for valid inputs

Add screenshots with your code and let's see it running and working pls


Not everyone have Jupiter installed to run your python code to check if it's correct.

(1) (2) (3) (4) (5) (Reply)

Anybody Here Know How One Can Password/encrypt Sqlite Database in C++? / Paid Job: A Magento 2.0 Plugin Developer Is Required For A Quick Job [Closed] / Why Will The Fg Allow Sidmach Tech Take 100% Control Of Jamb Website?

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 79
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.