Feature #6: Most Common Token
Explore how to determine the most frequently used token in a program string, excluding language keywords and syntax. Understand the step-by-step process of normalizing code, tokenizing it, and using data structures to count and identify the top token efficiently while analyzing time and space complexity.
We'll cover the following...
Description
For this feature of the language compiler, the program statements are given to us as a string. We want to determine the variable or function that is most commonly referred to in a program. In this process, we want to ignore the language keywords. For example, a keyword may be used more frequently than any variable or function. The language keywords are given as an array of strings.
Let’s say you are given the following program as input:
The list of keywords given to you is ["int", "main", "return"]. In this example, your function will return "value". Note that, your functions should ignore syntax, such as parentheses, operators, semicolons, etc.
Solution
We can solve this problem by normalizing the code string and processing it step by step. The complete algorithm is as follows:
-
First, we replace all the syntax, including parentheses, operators, semicolons, etc., with spaces. Now, the string only contains alphanumeric tokens.
-
Then, we split the code obtained from the previous step into
tokens. -
We iterate through the tokens to count the appearance of each unique token as keys, excluding the keywords.
-
We create a HashMap
count, which has tokens as keys and occurrences as values. -
In the end, we check the tokens in
countto find the token with the highest frequency.
Complexity measures
| Time complexity | Space complexity |
|---|---|