Problems - Set 1
Easy
Word Match
Design a method to find the frequency of occurrences of any given word in a book.
Approach 1: Using string split (One time)
package algo;
public class Problem1 {
public static void main(String[] args) {
String bookText = "Java is great. Java is powerful. Java is everywhere!";
String word = "Java";
int freq = getWordFrequency(bookText, word); // Output: 3
System.out.println(freq);
}
public static int getWordFrequency(String bookText, String word) {
if (bookText == null || word == null || word.isEmpty()) {
return 0;
}
String[] words = bookText.toLowerCase().split("\\W+"); // split on non-word characters
int count = 0;
for (String w : words) {
if (w.equals(word.toLowerCase())) {
count++;
}
}
return count;
}
}Approach 2: Using StringUtils method
Approach 3: Optimized for Multiple Calls
Preprocess the book text once into a frequency map. Then lookups are fast.
Medium
Pattern Matching
We are given:
A pattern string, e.g.,
"aabab"A value string, e.g.,
"catcatgocatgo"
We need to return true if we can map each unique character (a or b) in the pattern to a non-empty substring in the value so that replacing the pattern with its mapped substrings gives the original value.
Example
Pattern:
"aabab"Value:
"catcatgocatgo"
Let’s say
'a' = "cat"'b' = "go"
Substituting:
Pattern → "a a b a b" → "cat cat go cat go" → matches value → return true.
Constraints
Each
aandbmust map to one consistent substring throughout the pattern.aandbmust be different (but may be of any length).We can’t have
a = ""orb = ""(empty string is not allowed).
Approach
Count how many times
aandbappear in the pattern.Try all possible lengths of the substring assigned to
a.For each possible length of
a, calculate the length ofb(from remaining length of value).Try assigning substrings to
aandband check if the pattern reconstructs to the value.If we find a match, return
true. Otherwise returnfalse.
Arithmetic Evaluation
Given an arithmetic equation consisting of positive integers, +, -, * and / and no parentheses. Compute the result.
To evaluate an arithmetic expression like 2*3+5/6*3+15 (with no parentheses, only +, -, *, and /, and all positive integers), we must obey the order of operations:
Operator Precedence (BODMAS):
*and/(left to right)+and-(left to right)
Initialize:
result = 0lastTerm = 0operation = '+'
Read
2Operation is
'+', solastTerm = 2
* 3:Operation is
*, solastTerm = 2 * 3 = 6
+ 5:Add
lastTerm (6)toresult:result = 6Set
lastTerm = 5
/ 6:lastTerm = 5 / 6 ≈ 0.8333
* 3:lastTerm = 0.8333 * 3 ≈ 2.5
+ 15:Add
lastTerm (2.5)toresult:result = 6 + 2.5 = 8.5Set
lastTerm = 15
End of string → Add
lastTerm (15)to result → Final:8.5 + 15 = 23.5
This matches what BODMAS expects:
Last updated