I struggle with Big O complexity and this type of algo always confused me. We are looping through every number here in 2 loops so its O(n^2). But inside each iteration of the loops we have a substring + a concatenation. From what I understand the concatenation is optimized by the compiler to use essentially a string buffer. Does the substring just count as 4*n? So the total compute is nn(n+(4*n)) OR O(n^3). (n+(4*n)) comes from concatenation + the 4 substrings. Is my evaluation correct?
I am trying to solve this problem: https://leetcode.com/problems/maximum-swap
public int maximumSwap(int num) {
int biggestNum = num;
String sNum = String.valueOf(num);
for(int i = 0; i < sNum.length()-1; i++) {
for(int j = i+1; j < sNum.length(); j++) {
// 27364
String jSuffix = j == sNum.length()-1 ? "" : sNum.substring(j+1);
int newNum = Integer.valueOf(sNum.substring(0, i) + sNum.charAt(j) + sNum.substring(i+1, j) + sNum.charAt(i) + jSuffix);
if(newNum > biggestNum) biggestNum = newNum;
}
}
return biggestNum;
}