LeetCode 161: One Edit Distance Solution
Master LeetCode problem 161 (One Edit Distance), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
161. One Edit Distance
Problem Explanation
Explanation:
The problem asks us to determine if two given strings are one edit distance apart. An edit distance is defined as inserting a character, deleting a character, or replacing a character in one of the strings to make them equal.
To solve this problem, we can iterate through both strings simultaneously and compare the characters. If we find a difference, we need to check if it can be resolved within one edit operation. We can handle this by considering three cases:
- If the lengths of the strings differ by more than 1, they can't be one edit distance apart.
- If the lengths are equal, we can allow only one character to be different.
- If the lengths differ by 1, we can allow one string to have an additional character.
Time complexity: O(n) Space complexity: O(1)
:
Solution Code
class Solution {
public boolean isOneEditDistance(String s, String t) {
int m = s.length();
int n = t.length();
if (Math.abs(m - n) > 1) {
return false;
}
for (int i = 0; i < Math.min(m, n); i++) {
if (s.charAt(i) != t.charAt(i)) {
if (m == n) {
return s.substring(i + 1).equals(t.substring(i + 1));
} else if (m < n) {
return s.substring(i).equals(t.substring(i + 1));
} else {
return s.substring(i + 1).equals(t.substring(i));
}
}
}
return Math.abs(m - n) == 1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 161 (One Edit Distance)?
This page provides optimized solutions for LeetCode problem 161 (One Edit Distance) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 161 (One Edit Distance)?
The time complexity for LeetCode 161 (One Edit Distance) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 161 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 161 in Java, C++, or Python.