Skip to content

Commit a7f2406

Browse files
committed
Count chars in subtree mapping to string.
1 parent 6b098d1 commit a7f2406

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
=begin
2+
3+
Nodes in a Subtree
4+
You are given a tree that contains N nodes, each containing an integer u which corresponds to a lowercase character c in the string s using 1-based indexing.
5+
You are required to answer Q queries of type [u, c], where u is an integer and c is a lowercase letter. The query result is the number of nodes in the subtree of node u containing c.
6+
Signature
7+
int[] countOfNodes(Node root, ArrayList<Query> queries, String s)
8+
Input
9+
A pointer to the root node, an array list containing Q queries of type [u, c], and a string s
10+
Constraints
11+
N and Q are the integers between 1 and 1,000,000
12+
u is an integer between 1 and N
13+
s is of the length of N, containing only lowercase letters
14+
c is a lowercase letter contained in string s
15+
Node 1 is the root of the tree
16+
Output
17+
An integer array containing the response to each query
18+
Example
19+
1(a)
20+
/ \
21+
2(b) 3(a)
22+
s = "aba"
23+
RootNode = 1
24+
query = [[1, 'a']]
25+
Note: Node 1 corresponds to first letter 'a', Node 2 corresponds to second letter of the string 'b', Node 3 corresponds to third letter of the string 'a'.
26+
output = [2]
27+
Both Node 1 and Node 3 contain 'a', so the number of nodes within the subtree of Node 1 containing 'a' is 2.
28+
29+
=end
30+
31+
class Node
32+
attr_reader :value
33+
attr_accessor :children
34+
35+
def initialize(value, children)
36+
@value = value
37+
@children = children
38+
end
39+
end
40+
41+
# Should use the substring to count.
42+
def count_of_nodes(root, queries, s)
43+
output = []
44+
queries.each do |query|
45+
r_node = nil
46+
queue = [root]
47+
while(queue.size > 0)
48+
temp_node = queue.shift
49+
if(temp_node.value == query[0])
50+
r_node = temp_node
51+
break
52+
else
53+
queue = queue + temp_node.children
54+
end
55+
end
56+
queue = [r_node]
57+
count = 0
58+
while(queue.size > 0)
59+
temp_node = queue.shift
60+
if(s[temp_node.value-1] == query[1])
61+
count+=1
62+
end
63+
queue = queue + temp_node.children
64+
end
65+
output << count
66+
end
67+
output
68+
end
69+
70+
node4 = Node.new(4, [])
71+
node1 = Node.new(2, [node4])
72+
node2 = Node.new(3, [])
73+
node3 = Node.new(1, [node1, node2])
74+
75+
p count_of_nodes(node3, [[1, 'a']], 'abaa')

0 commit comments

Comments
 (0)