Category: Easy | Concepts used: String references, string concatenation, substring parsing, reference vs value allocation
Problem Statement
Given two strings a and b, swap their values.
Input : a = "cat", b = "dog" Output: a = "dog", b = "cat"
Input : a = "", b = "hi" Output: a = "hi", b = ""
Examples (with edge scenarios)
| # | a (before) | b (before) | a (after) | b (after) | Note |
|---|---|---|---|---|---|
| 1 | "cat" | "dog" | "dog" | "cat" | Typical strings |
| 2 | "" | "hi" | "hi" | "" | Empty string check |
| 3 | "same" | "same" | "same" | "same" | Identical values |
| 4 | null | "hi" | "hi" | null | Null-safety reference check |
โ ๏ธ Common Beginner Mistake
Mistake Impact Fix Trying arithmetic operators on strings Compile-time syntax error Use string references or concatenation techniques Assuming concatenation-based swaps are faster Extremely slow and memory-intensive due to String immutability Use the temporary variable approach for standard code
Before You Code: Clarify the Contract
Before choosing an algorithm, confirm how null and empty strings should behave, whether comparison is case-sensitive, and whether spaces or punctuation count. Java char values are UTF-16 code units, not always complete human-visible Unicode characters, so international text may require code points or grapheme-aware libraries.
Analogy: Labeling Folders
Imagine you have two folders on your desk:
- Folder A is labeled โCatโ and contains documents.
- Folder B is labeled โDogโ and contains documents.
Swapping them:
- Solution 1 (Reference Swap): You simply swap the labels on the folders. The folders themselves donโt move; you just swap the label pointers. This is instant and takes no physical effort.
- Solution 2 (Concatenation and Slicing): Instead of swapping labels, you take the documents from both folders, staple them together into one giant stack (concatenation), place them in Folder A, and then use scissors to cut them apart (substrings) to separate the papers back into the respective folders. This takes much more work, wastes paper, and is highly prone to mistakes!
Solution 1 โ Using a Temp Variable (Standard & Recommended)
This is the standard, production-ready solution in Java.
Intuition
In Java, strings are objects, and string variables are references (pointers) to locations in the heap memory (String Pool). When we swap them using a temporary variable, we are only swapping the references, not copying the actual text data. This runs in constant (O(1)) time.
public class SwapStringsWithTemp {
public static void main(String[] args) {
String a = "cat", b = "dog";
System.out.println("Before: a=" + a + ", b=" + b);
String temp = a; // temp now references "cat"
a = b; // a now references "dog"
b = temp; // b now references "cat"
System.out.println("After: a=" + a + ", b=" + b);
}
}
Output:
Before: a=cat, b=dog
After: a=dog, b=cat
Solution 2 โ Concatenation & Slicing, No Temp Variable
This approach swaps strings without using a temporary variable, using concatenation.
Intuition
By appending b to a, we create a single combined string ("catdog"). We can then use indices and lengths to extract the original segments back into b and a.
public class SwapStringsNoTemp {
public static void main(String[] args) {
String a = "cat", b = "dog";
System.out.println("Before: a=" + a + ", b=" + b);
a = a + b; // a becomes "catdog"
// Extract original a into b: substring from 0 to (length of "catdog" - length of "dog")
b = a.substring(0, a.length() - b.length()); // b becomes "cat"
// Extract original b into a: substring starting from length of b ("cat") to the end
a = a.substring(b.length()); // a becomes "dog"
System.out.println("After: a=" + a + ", b=" + b);
}
}
Output:
Before: a=cat, b=dog
After: a=dog, b=cat
๐ Visual Sequence Diagram
sequenceDiagram
participant a as Variable A ("cat")
participant b as Variable B ("dog")
Note over a, b: Concatenation Swap (No Temp Variable)
a->>a: Step 1: Concatenate (a = a + b -> "catdog")
b->>b: Step 2: Slice head (b = a.substring(0, len(a) - len(b)) -> "cat")
a->>a: Step 3: Slice tail (a = a.substring(len(b)) -> "dog")
Note over a, b: After Swap: a = "dog", b = "cat"
Interviewer Insights
This question highlights the difference between primitive data types and heap objects.
Follow-up questions you might get:
- โWhat are the performance implications of Solution 2?โ โ Solution 2 is highly inefficient. In Java,
Stringobjects are immutable. When we performa = a + b, Java creates a new String in memory. When we callsubstring(), more string objects are allocated. This takes (O(N+M)) time and space. Conversely, Solution 1 only swaps 64-bit reference pointers in the stack, taking (O(1)) time with zero extra heap allocations. - โWhat if one of the strings is null?โ โ Solution 1 handles it safely. Solution 2 will throw a
NullPointerExceptionwhen trying to call.length()or.substring()on a null reference. Always mention this null vulnerability of the concatenation approach.
Quick Recap
| Approach | Heap Allocation | Time Complexity | Null Safety | Interview Signal |
|---|---|---|---|---|
| Temp Variable | None (reference pointer swap) | (O(1)) | Yes | Standard, production-grade, highly efficient |
| Concatenation / Substring | High (creates multiple new String objects) | (O(N+M)) | No (throws NPE) | Demonstrates puzzle solving, but carries performance bottlenecks |
- Author
- TechByteByByte Editorial Team
- Reviewed by
- TechByteByByte Admin
- Published
- Last reviewed