Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Compare dotted version strings numerically part by part (missing parts count as 0); return 1, 0 or −1.
Problem: Compare dotted version strings numerically part by part (missing parts count as 0); return 1, 0 or −1.
def cmp_ver(a, b):
x = list(map(int, a.split("."))); y = list(map(int, b.split(".")))
n = max(len(x), len(y)); x += [0] * (n - len(x)); y += [0] * (n - len(y))
return (x > y) - (x < y)
print(cmp_ver("1.10", "1.9"), cmp_ver("2.0.0", "2"), cmp_ver("3.01.2", "3.1.10"))What is printed?- A. 1 0 -1
- B. -1 0 -1
- C. 1 1 -1
- D. 1 0 1
Correct answer: A. 1 0 -1
Parts are integers, so 10 > 9 (string comparison would say "10" < "9") and "01" equals 1. Padding makes "2" equal to "2.0.0". Then [3, 1, 2] < [3, 1, 10] by list comparison → −1. O(n).
More Coding Interview Problems questions
- Problem: Multiply two non-negative integers given as decimal strings without converting them to int; digit i·j lands in position i + j + 1…
- Problem: Reverse the bit order of an 8-bit value (bit 0 ↔ bit 7, …). python def rev8(x): r = 0 for in range(8): r = (r << 1) | (x & 1); x…
- Problem: Java int shifts: arithmetic >> keeps the sign, logical >>> fills with zeros, and shifting into the sign bit overflows. java int a…
- Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:]) in O(n), then use it on pattern + '' + text to…
- Problem: Count non-empty substrings with equal numbers of 0s and 1s where all 0s are grouped together and all 1s are grouped together…
- Problem: Find the lexicographically smallest rotation of a string in O(n) with a two-candidate comparison (Booth-style), and compare it…