Skip to content

Feature/swap nodes algo #569

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/hackerrank/interview_preparation_kit/search/swap_nodes_algo.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,21 +67,23 @@ def traverse_in_order_collector(

def build_tree(indexes: List[List[int]]) -> Node:

indexes_copy = indexes[:]
root: Node = Node(__ROOT_VALUE__)
node_collector: Dict[int, list[Node]] = {}
node_collector: Dict[int, list[Node]]

while len(indexes) > 0:
while len(indexes_copy) > 0:
node_collector = {}
traverse_in_order_collector(
root,
node_collector,
__INITIAL_LEVEL__,
callback_collect_nodes)

last_level: int = list(node_collector)[-1]
last_level: int = sorted(list(node_collector))[-1]

for i in range(0, min(len(indexes), len(node_collector[last_level]))):
for i in range(0, min(len(indexes_copy), len(node_collector[last_level]))):
current_node: Node = node_collector[last_level][i]
new_element: List[int] = indexes.pop(0)
new_element: List[int] = indexes_copy.pop(0)

if new_element[0] != -1:
current_node.left = Node(new_element[0])
Expand All @@ -91,7 +93,7 @@ def build_tree(indexes: List[List[int]]) -> Node:
return root


def plain_tree(root: Node) -> List[int]:
def flatten_tree(root: Node) -> List[int]:
node_collector: Dict[int, list[Node]] = {}

node_collector = traverse_in_order_collector(
Expand Down Expand Up @@ -136,7 +138,7 @@ def swap_nodes(indexes: List[List[int]], queries: List[int]) -> List[List[int]]:

node_collector = dict(sorted(node_collector.items()))

plain = plain_tree(tree) # original
plain = flatten_tree(tree) # original

LOGGER.debug('Plain tree: %s', plain)

Expand All @@ -146,7 +148,7 @@ def swap_nodes(indexes: List[List[int]], queries: List[int]) -> List[List[int]]:
for node in node_list:
swap_branch(node)

plain = plain_tree(tree)
plain = flatten_tree(tree)
output.append(plain)

return output
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,34 @@
{
"title": "Sample 0",
"nodes": [[2, 3], [-1, -1], [-1, -1]],
"flattened": [2, 1, 3],
"queries": [1, 1],
"answer": [[3, 1, 2], [2, 1, 3]]
"expected": [[3, 1, 2], [2, 1, 3]]
},
{
"title": "Sample 1",
"nodes": [[2, 3], [-1, 4], [-1, 5], [-1, -1], [-1, -1]],
"flattened": [2, 4, 1, 3, 5],
"queries": [2],
"answer": [[4, 2, 1, 5, 3]]
"expected": [[4, 2, 1, 5, 3]]
},
{
"title": "Sample 2",
"nodes": [[2, 3], [4, -1], [5, -1], [6, -1], [7, 8], [-1, 9],
[-1, -1], [10, 11], [-1, -1], [-1, -1], [-1, -1]],
"flattened": [6, 9, 4, 2, 1, 7, 5, 10, 8, 11, 3],
"queries": [2, 4],
"answer": [[2, 9, 6, 4, 1, 3, 7, 5, 11, 8, 10],
"expected": [[2, 9, 6, 4, 1, 3, 7, 5, 11, 8, 10],
[2, 6, 9, 4, 1, 3, 7, 5, 10, 8, 11]]
},
{
"title": "Sample Test Case 1",
"nodes": [[2, 3], [4, 5], [6, -1], [-1, 7], [8, 9], [10, 11], [12, 13],
[-1, 14], [-1, -1], [15, -1], [16, 17], [-1, -1], [-1, -1],
[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
"flattened": [4, 12, 7, 13, 2, 8, 14, 5, 9, 1, 15, 10, 6, 16, 11, 17, 3],
"queries": [2, 3],
"answer": [[14, 8, 5, 9, 2, 4, 13, 7, 12, 1, 3, 10, 15, 6, 17, 11, 16],
"expected": [[14, 8, 5, 9, 2, 4, 13, 7, 12, 1, 3, 10, 15, 6, 17, 11, 16],
[9, 5, 14, 8, 2, 13, 7, 12, 4, 1, 3, 17, 11, 16, 6, 10, 15]]
}
]
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,57 @@
from pathlib import Path

from ....hackerrank.lib.loader import load_test_cases
from .swap_nodes_algo import swap_nodes, build_tree, plain_tree, swap_branch
from ....hackerrank.lib.node import Node
from .swap_nodes_algo import swap_nodes, build_tree, flatten_tree, swap_branch

FILE_PATH = str(Path(__file__).resolve().parent)
TEST_CASES = load_test_cases(FILE_PATH + '/swap_nodes_algo.testcases.json')


class TestSwapNodesAlgo(unittest.TestCase):

def test_swap_nodes(self):

for _, _tt in enumerate(TEST_CASES):

self.assertEqual(
swap_nodes(_tt['nodes'], _tt['queries']), _tt['answer'],
swap_nodes(_tt['nodes'], _tt['queries']), _tt['expected'],
f"{_} | swap_nodes({_tt['nodes'], _tt['queries']}) must be "
f"=> {_tt['answer']}")
f"=> {_tt['expected']}")

def test_swap_branch(self):

t_input = None
t_result = swap_branch(t_input)
answer = None
expected = None

self.assertEqual(
t_result,
answer,
expected,
f"swap_branch({t_input}) must be "
f"=> {answer}"
f"=> {expected}"
)

def test_build_tree_and_plain(self):

for _, _tt in enumerate(TEST_CASES):

t_to_test: Node = build_tree(_tt['nodes'])
t_result: list[int] = flatten_tree(t_to_test)

self.assertEqual(
t_result, _tt['flattened'],
f"{_} | flatten_tree({_tt['nodes']}) must be {_tt['expected']}")

def test_build_tree_empty(self):

t_input = []
t_to_test = build_tree(t_input)
t_result = plain_tree(t_to_test)
answer = [1]
t_result = flatten_tree(t_to_test)
expected = [1]

self.assertEqual(
t_result,
answer,
expected,
f"build_tree({t_input}) must be "
f"=> {answer}"
f"=> {expected}"
)