I am struggling to understand the time complexity of this solution. This question is about converting number to English words.
For Example, Input: num = 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
StringBuilder insert() has O(n) time Complexity.
I suspect the time Complexity is O(n^2). But I am not sure. Where n is the number of digits.
Link to question: englishToWords
There is my code:
Code:
class Solution {
private final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
private final String[] LESS_THAN_TWENTY = {"", "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] TENS = {"", "", "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"};
//O(n) solution
public String numberToWords(int num) {
if (num == 0){
return "Zero";
}
StringBuilder sb = new StringBuilder();
int index = 0;
//this contributes towards time complexity
while (num > 0) {
if (num % 1000 > 0) {
StringBuilder tmp = new StringBuilder();
helper(tmp, num % 1000);
System.out.println(index);
System.out.println("tmp: "+ tmp);
tmp.append(THOUSANDS[index]).append(" ");
//I suspect the time complexity will increase because of this to O(n^2)
sb.insert(0, tmp);
}
index++;
num = num / 1000;
}
return sb.toString().trim();
}
private void helper(StringBuilder tmp, int num) {
if (num == 0) {
return;
} else if (num < 20) {
tmp.append(LESS_THAN_TWENTY[num]).append(" ");
return;
} else if (num < 100) {
tmp.append(TENS[num / 10]).append(" ");
helper(tmp, num % 10);
} else {
tmp.append(LESS_THAN_TWENTY[num / 100]).append(" Hundred ");
helper(tmp, num % 100);
}
}
}
Time Complexity is O(n) where n is the number of digits in the given number. We are traversing the number once.
I confirmed this from my few friends working in Cisco and Google.