Java substring() behavior in permutations algorithm

💡 While implementing string permutations in Java, I noticed a small detail about 'substring()' that many developers overlook. Here’s the example I was working on. Find all permutations of "ABC". Total permutations: 3! = 6 ABC ACB BAC BCA CAB CBA The idea behind the algorithm is simple. At each step we: • pick one character • append it to the answer • recurse on the remaining characters A common Java implementation looks like this: public static void permutation(String str, String ans) { if (str.isEmpty()) { System.out.println(ans); return; } for (int i = 0; i < str.length(); i++) { char current = str.charAt(i); String newStr = str.substring(0, i) + str.substring(i + 1); permutation(newStr, ans + current); } } Initial call: permutation("ABC", "") While walking through the code, an interesting Java behavior appears. Consider this case: str = "ABC" i = 2 // character 'C' The code executes: str.substring(0, 2) → "AB" str.substring(3) → "" Why doesn't `substring(3)` throw an error? Because in Java: "#substring(beginIndex)" returns the substring from #beginIndex to the end of the string. If: beginIndex == str.length() Java simply returns an empty string, not an exception. So the expression becomes: "AB" + "" Result: "AB" This small language detail allows the permutation logic to work without extra boundary checks. Sometimes the most useful insights while solving DSA problems come from understanding how the programming language behaves at edge cases. #Java #DSA #Recursion #Algorithms #CodingInterview

  • No alternative text description for this image

Very helpful, keep posting ☺️

Like
Reply

To view or add a comment, sign in

Explore content categories