Compare Version Numbers
LeetCode 165 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Parse revisions in lockstep; missing = 0.
मैंने Compare Version Numbers (LeetCode 165) ऐसे हल किया — Parsing / Conversion पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Compare revision by revision. Parse each revision as a number on the fly (so leading zeros vanish), treat missing revisions as 0, and return at the first difference.
Approach
- 1
Pointers i and j into each version string.
- 2
Read digits up to the next '.' into n1 and n2.
- 3
Different → return 1 or −1; equal → skip the dots and continue.
- 4
All equal → 0.
मैंने कैसे हल किया
Two-pointer parsePythonO(m+n) time · O(1) space
class Solution:
def compareVersion(self, version1, version2):
i = 0
j = 0
v1len = len(version1)
v2len = len(version2)
while i < v1len or j < v2len:
n1 = 0
n2 = 0
while i < v1len and version1[i] != ".":
n1 = n1 * 10 + int(version1[i])
i += 1
while j < v2len and version2[j] != ".":
n2 = n2 * 10 + int(version2[j])
j += 1
if n1 > n2:
return 1
elif n1 < n2:
return -1
i += 1
j += 1
return 0Compare Version Numbers — अक्सर पूछे जाने वाले प्रश्न
Compare Version Numbers के पीछे intuition क्या है?
Compare revision by revision. Parse each revision as a number on the fly (so leading zeros vanish), treat missing revisions as 0, and return at the first difference.
Compare Version Numbers (LeetCode 165) कैसे हल करें?
1. Pointers i and j into each version string. 2. Read digits up to the next '.' into n1 and n2. 3. Different → return 1 or −1; equal → skip the dots and continue. 4. All equal → 0.
Compare Version Numbers की time और space complexity क्या है?
Time: O(m + n)। Space: O(1)। (Accepted approach: Two-pointer parse।)
Compare Version Numbers में आम गलतियाँ क्या हैं?
'1.0' and '1.0.0.0' are equal.