# Swap Nodes [Algo]

# Swap Nodes [Algo]

xialin + 14 comments One of the most ambiguous question on HackerRank. I wish I could down vote the problem description.

whoiscris + 5 comments It's not ambiguous at all. It's not a very deep problem. If you code it clean you won't have any difficulties. Btw, it uses a lot of concepts from the other problems of the Trees section: https://www.hackerrank.com/domains/data-structures/trees.

xialin + 0 comments It's not about difficulty. it's about clarity.

mark55 + 1 comment Yes, it is ambiguous. In one case it says to print the traversal after each swap operation (which for each T there can be more than 1), then it implies that the traversal only needs to be printed T times.

It would not have taken much effort to make this clear.

vucislav + 1 comment Actually, a swap operation consists of more swaps, see the definition for

**Swapping**and for**Swap operation**, so the problem is not ambiguous when it comes to that part.- LT
lingbo19_tang + 1 comment Input is somehow ambiguous, for example

3

2 3

-1 -1

-1 -1

2

1

1

How can you assume that the root is 1 and another child is 2? And why are you swapping 1 twice? And what's the meaning of the -1 -1, -1 -1. Makes no sense to me.

- JY
jack_yang243 + 1 comment I think all the information you need is in the problem description. It's just a lot to take in.

The tree with N nodes is rooted at the node with index 1 as described in the Swapping operation section. So the root of the tree is 1.

-1 is used to represent a null node, as described in the Input Format section. For example, the -1s in the second of the N lines mean that the node with index 2 has NULL pointers for both of its children. Similarly, the -1s in the third of the N lines means that the node with index 3 also has NULL pointers for both of its children.

I don't think there's a particular reason why we swap at level 1 twice. The sample inputs are just used to illustrate an example (Sample Input/Output #00 correspond to Test Case #00 in the Explanation section).

- AA
alaniane + 0 comments Index 1 and the value of the root are not the same. Binary tree root can contain any value. That part of the problem declaration is ambiguous. For example:

5 / \ 3 2 / \ / \ 10 6 9 17

Is still a binary tree. It's not sorted, but that does not disqualify it as a binary tree.

ypahalajani + 0 comments I got to learn a lot!

rishabh_ags + 0 comments Yes it's as "not ambiguous" as the number of downvotes on you comment :P

rasik210 + 1 comment I agree with you specially with the fact that it uses a lot of concepts from the other problems of trees section. I was able to achieve it using a simple algorithm:

- Build the tree.
Repeat below steps for every value of k

- Perform level order traversal (BFS) of the entire tree.
- At each level, if level is a multiple of k then swap the

child of the nodes at that level. - After the level order traversal is done, perform in order traversal (DFS) to print the tree nodes data.

I used below definition of a node while building the tree:

`class TreeNode { public int Data { get; set; } public TreeNode LeftChild {get; set;} public TreeNode RightChild { get; set; } public int Depth { get; set; } }`

- WL
h670363997 + 0 comments My algorithm is the same as yours，but i did not pass all the test.

- H
kenji4861 + 1 comment "Given a tree and a integer, K, we have to swap the subtrees of all the nodes who are at depth h, where h ∈ [K, 2K, 3K,...].

You are given a tree of N nodes where nodes are indexed from [1..N] and it is rooted at 1. You have to perform T swap operations on it, and after each swap operation print the inorder traversal of the current state of the tree."

Definitely had to read over it 3 times..

- PW
walkerp07 + 0 comments Thanks.

- KU
kimberlyu + 1 comment I agree! This question was ambiguous. "Given a tree and a integer, K, we have to swap the subtrees of all the nodes who are at depth h, where h ∈ [K, 2K, 3K,...]." This part was kind of confusing because I associated h with being the height. Also, I didn't quite understand the mathematical notation h ∈ [K, 2K, 3K,...] meant to swap nodes at every depth that was a multiple of K until I looked it up. If that was explained, it would have been a lot less confusing.

- GK
garykhong + 0 comments Thanks for explaining the multiples of every depth. The problem description and examples do not make it very clear at all.

- JH
juharri3 + 0 comments I didn't find it as much ambiguous as convoluted. I mean the code to load the tree was more complex than the in order printing or the swapping.

- AS
acs2010 + 0 comments I totally agree. Could someone please describe the problem for me in English ?

UWUTM8 + 0 comments I was thinking the same thing after 20 minutes!

VINAY_VKK + 0 comments Yes but thank god they gave explanation with examples, if not it would have been even worse than now to understand

- NC
NandiChaurasiya + 0 comments I too found this problem as one of better problem where I learned lot of things.

randspence + 0 comments I don't think ambiguous is the right word here. Everything you need to do the problem is here, its just not worded very clearly/concisely. This is a good problem, with a terrible description.

- AM
7heaven + 0 comments The swapping part of the question was actually simple. Getting the input and converting into the tree was actually a bit tedious because of the way the input was given. Actual swapping could be done just with a simple addition to normal inorder traversal once the tree was built(which required queue, to simplify the process of creating it.) Here's my swap function. Hope it helps in understanding the problem for anyone who actually found swapping ambiguous:

void swap(int k,struct node* root,int level) { if(root!=NULL) { if(level%k == 0) { t0 = root->left; root->left = root->right; root->right = t0; t0 = NULL; } swap(k,root->left,level+1); cout<<root->data<<' '; swap(k,root->right,level+1); } }

- MU
markuhl327 + 0 comments This is one of those questions such that, if I were actually to come across this in industry, I would read it once or twice through and then go talk to the person requesting such an algorithm and discuss it. Even the input set structure is poorly described..

kamanashisroy + 0 comments I wish someone delete this problem. It does not worth my time.

- SS
stefanks + 10 comments In python had to change recursion limit to work on the last two test inputs

import sys sys.setrecursionlimit(15000)

- JZ
carborundum + 1 comment I used a loop with a deque as a stack instead to get around that problem

- HA
magoarcano + 1 comment I used a loop with a deque as a queue too but it didn't get around that problem with that solution

- R
reddeadya + 0 comments You can use even the list() and it works. See the "Iterative InOrder traversal" example: here on wiki

- J
j_b_shteyn + 0 comments Thanks for the tip

- J
jellybeanfiend + 1 comment Amazing! This is exactly what I hoped to find in the comments. Thanks!

shukla1804 + 1 comment what prerequisite i need to solve this question

- SS
shshnk28 + 2 comments solve level order traversal first. the logic here is similar.

- try to create a tree from the input.
- get the height of the tree.
- read the next set of input. go to the particular level and swap the nodes.

- AM
ayeshamatloob + 1 comment i'm confused, we have to swap nodes(means that whole node containing its child nodes are also moved form left to right or right to left) or we have to swap nodes data.

vinayb21 + 0 comments We have to swap nodes not their data.

- MS
manthan_learner + 1 comment I did the same thing but am getting time out in test cases 6,7,10 and 11. Can any one suggest some thing?

coder08122014 + 0 comments same here bro, i first created a tree then inserted nodes acoordingly on the basis of input then swapped but it is giving timeout in test case 6,7,10,11. please provide me an update as soon as u get it,and ill do the same

bibhash + 0 comments Thank you so much! Would never have figured that out.

Keerthanss + 0 comments Thank you!

mulberrylane + 0 comments Awesome, I finally got every test past! Thanks.

imhktc + 0 comments I never knew there was recursion limit, thanks!!

- MW
GeoMatt22 + 0 comments Ha! Good trick.

It was fun to work out the in-order traversal using a list-based stack though :)

By the way, a recursion limit of 1200 is sufficient. (1024 is too small for sure.)

- AJ
ayush199429 + 0 comments Thanks a lot!!

- J
jimmy_valentine + 0 comments You saved my life bro. I just started coding in python so didn't know that such a thing exists. I was getting this error for past half an hour!Thanks

asharm36 + 2 comments I usually agree with Hackerrank's difficulty ratings, however I feel given how tedious this problem is, it should be a "Moderate" at least

badonkadonk + 1 comment I agree. I think building a tree from the input stream, combined with the wording of the question really adds to the complexity of this rather basic problem.

Should be a "Moderate".

dekoder + 0 comments solve it for fun why runnning behind "rating" unless you solving it in live competition. Just sayin!

- AD
alan_davies + 1 comment It took as much time to get the stdin reading working as it did to do all the previous exercises in this section. The actual 'swap' function was trivial though.

- VS
vikrambs + 0 comments True.. The problem is all about an array representation of non binary tree.

realq86 + 2 comments Solved the problem but had to. 1. Create node object. 2. Create a breathFirst to read input. 3. Create a depthFirst to change height. 4. Create a Inorder to print.

Took 3 hours total. Is is listed as "Easy?" Is there an easier way than the apporche I did?

ludopulles + 3 comments I'm not sure about your breadth-first approach to read input. You should just initialize your array of length n with left and right child.

About the time, if you practice more, you will see that you can solve problems faster and faster! This one took me 10 minutes :).

realq86 + 3 comments Hi, Thanks for the tip. So you mean you just used an array and didn't create a binary tree data structure?

I actually created a tree, loaded it with data swap the subtree, and traverse the tree to print the output.

Sounds like I over engineered! Would you like to exchange solutions?

ludopulles + 11 comments Hmm, well, I used an array but it represents a binary tree, so I would call it a binary tree data structure :P. Here is my solution: http://ideone.com/Fml7Sm You can see, I didn't use a BFS but I iterated over the array. This is possible because a swap won't change the depth of a node, so the order in which you swap nodes doesn't matter.

realq86 + 0 comments You serialized the tree! In this case a good call, since the input is serialized to begin with.

- H
HarryCho + 0 comments great answer!

- KS
keyul + 0 comments Thanks for idea of Two different arrays to store left and right node.

- V
raina_venki + 1 comment Hi, your code is not giving any output for this following input...

5

2 2

3 -1

-1 3

-1 -1

-1 -1

2

1

1

ludopulles + 3 comments The tree you give, is not a tree:

- the right child of node 3 is itself
- both the left and right child of node 1 are 2.

So we can assume that this input won't appear as one of the test cases.

- V
raina_venki + 0 comments sorry i didn't get you.... 1 is the root, 1st 2 is left child of 1 and 2nd 2 is the right child of 1,

1st 3 is the left child of 1st 2 and right child of 1st 2 is null,

2nd 3 is the right child of 2nd 2 and left child of 2nd 2 is null,

both children of both 3 will be null.... this is the tree right.......

- V
raina_venki + 1 comment and i don't understand why you mentioned that both left and right child of node 1 are 2.....yeah...i can be right....since it is a binary tree not a binary search tree....and there no such rule that there shouldn't be duplicate nodes....and both the children are greater than their parent....

ludopulles + 1 comment The 4th line of input is

`-1 3`

, which shows the left and right child of node 3. Nodes start from 1. So there is a cycle 3 -> 3. Therefore it is not a tree.- V
raina_venki + 1 comment that fourth line of input are children of the right child of root node right....not the children of 3....

ludopulles + 1 comment Uhm, no... Check the input format. It explains it quite well.

aayush_break + 0 comments [deleted]

- G
gschoen + 1 comment It's a tree but with nodes that have duplicate data.

1 / \ 2 2 / \ 3 3

In this case, swapNodes won't change the nature of the tree.

- V
raina_venki + 0 comments it is not mentioned in the problem.....or in the input conditions........

- JK
aj510 + 0 comments Wow, very nice! I did the same as realq86 (created tree data struct and methods). Thank you for sharing your code! Clever :D

- VV
Zen_Programmer + 0 comments Thank you!! wonderful code...Helped me when i was stuck tring to figure out the depth!

ypahalajani + 0 comments You used 2 arrays for storing left and right children. Genius! BTW: how do you come with such great logic and how much time does it take, GENERALLY ?

- P
prasanthsri09 + 0 comments Upvote! Upvote! Upvote!

- AS
spartacus_arena + 0 comments @ludopulles thanks for your solution.

ravin_dra + 0 comments this is so cool

- ML
long0133 + 1 comment Your solution may fail if input numbers are not in increment order. For example,

3

3 -1

2 -1

-1 -1

2

1

1

(while it works when in order:

3

2 -1

3 -1

-1 -1

2

1

1 )

One more example:

5

4 5

2 -1

-1 3

-1 -1

-1 -1

1

1

The problem is because you use the input value as array index.

- CP
paucarchris + 0 comments Check your examples again, they're not BST. The first example says node 3 is a child of node 1, yet node 2 is a child of node 2?

Second example works because it's a BST. Third example says node 4 and 5 are children of node 1, node 2 is its own child, node 3 is its own child.

- EC
chued + 0 comments While it is over engineering, your approach seems to be the learning intent of the problem. All 4 steps are outputs from prior problems. It should be a re-create with minor modifications exercise, hence the 'easy'. The wording of the problem, on the other hand...

coder08122014 + 0 comments exactly i also did the same but i guess theres more optimal solution present

SachitMNayak + 0 comments yup! same here !

nikolaijivkov + 0 comments It certainly took a lot of writing, but I think it's easy becouse all of these tasks we had to solve in order to get to this one.

I've certainly learned a lot from this site :)

waitingkuo + 0 comments same here. the algorithm is easy, but its implementation is so hard

sarthakgarg + 3 comments This question is by no means an 'Easy' one. It is really time intensive since it needs to be started from scratch. Also, if possible, then please simplify the wording of the question.

cassiojp + 0 comments It should be easy to append pairs to an array and traverse the tree from there, what was your approach?

EdwardSkrod + 1 comment I agree. The wording is very difficult to understand.

harshittest + 0 comments Make it simple to understand.

bennattj + 0 comments Well I disagree. I've found many "easy" problems considerably more difficult than this one. I don't really understand the confusion with reading the input.

First, I used a Node class, which held the level for each node (along with the label and left and right children). Then stored the nodes as an array of Nodes (seemed pretty obvious considering the labeling). Finally I used a Map (HashMap) which held a list of nodes at each level.

So reading was pretty straightforward: iterate 0-N to get children. Each time you are setting the children of node[i], further you can set the level of the children by adding one to node[i]'s level. Add the children nodes to the list for that particular level.

Then swapping is incredibly easy: find the list at each level and swap all of those nodes' children. Use previous algorithm (or in my case a much simpler recursive algorithm) to print the new tree in-order.

I know space-wise, that's definitely not the most efficient. But in terms of time-complexity, the most expensive operation is printing the tree.

The one part that I thought about that could have made it more difficult is if they didn't give the nodes "in order" (which I see no where that this was necessary). So for instance, the second node might not have had it's level set when it's children were specified (say because the first node didn't contiain node "2"). I figured if that was the case, you could do some kind of bubble iteration after all of the nodes were parsed. Basically keep iterating through all of the nodes until all of the levels were set

imaginationsuper + 5 comments Use either Iterative or Recursive method to swap nodes:

import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; class Node { int data; int depth; Node left, right; Node(int data, int depth){ this.data = data; this.depth = depth; } } public class Solution { public static void swap_nodes(Node root, int K){ /*Queue<Node> nodes = new LinkedList<Node>(); nodes.offer(root); Node cur; while (!nodes.isEmpty()){ cur = nodes.poll(); if (cur.depth%K == 0){ Node tmp = cur.left; cur.left = cur.right; cur.right = tmp; } if (cur.left != null) nodes.offer(cur.left); if (cur.right != null) nodes.offer(cur.right); }*/ if (root != null){ if (root.depth%K == 0){ Node tmp = root.left; root.left = root.right; root.right = tmp; } swap_nodes(root.left, K); swap_nodes(root.right, K); } } public static void inorder_print(Node root){ if (root != null){ inorder_print(root.left); System.out.print(root.data+" "); inorder_print(root.right); } } public static void print_nodes(Node root, int K){ swap_nodes(root, K); inorder_print(root); System.out.println(); } public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); Node root = new Node(1, 1); Node cur = root; Queue<Node> nodes = new LinkedList<Node>(); nodes.offer(cur); while (N-->0){ cur = nodes.poll(); int leftData = sc.nextInt(); int rightData = sc.nextInt(); cur.left = (leftData==-1)? null: new Node(leftData, cur.depth+1); cur.right = (rightData==-1)? null: new Node(rightData, cur.depth+1); if (cur.left != null && cur.left.data!= -1) nodes.offer(cur.left); if (cur.right != null && cur.right.data!=-1) nodes.offer(cur.right); } int T = sc.nextInt(); while (T-->0){ int K = sc.nextInt(); print_nodes(root, K); } } }

- GZ
garyzhang2681 + 0 comments Almost the same as mine!

shubhamv23 + 0 comments [deleted]- AO
anupam_1482002 + 0 comments HI @imaginationsuper , Could you please let me know why you are checking if (root.depth%K == 0)?

jashan_bhullar + 0 comments Great Solution ,Thanks

- RM
rahulmbw + 0 comments Great Solution

pburakov + 0 comments The problem is not hard at all, but very poor description and badly structured input make it a lot harder than it should be. I would suggest some areas for clarification. Is

*i*the line number? Or is it node index? It's actually both, and the right answer is that null node should not be indexed but line numbers go on. It's not immediately clear if*K*is applied to depth or height, because below for some reason letter*h*is used to represent the depth. Use of index in the input and other constrains literally enforce the use of array upon the user.

- BC
bhupathi_chary + 0 comments Descrption of the problem should have been better. I spent 80% of the time in understanding it only.

oguzhanyalcin + 0 comments The worst question I've read....

- OC
oc_misc + 0 comments Very bad description. Is there anyone who can rewrite this question in a sensible way? I would love to attempt it if that happens.

Sort 257 Discussions, By:

Please Login in order to post a comment