Question 31
MediumWhy is building a long string with repeated += in a loop slow in Java?
- A.
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Data Structures and Algorithms
Why is building a long string with repeated += in a loop slow in Java?
Each += creates a new String object and copies the old contents, making it O(n²) overall
+= is not allowed on strings
Strings can't be concatenated
Java strings are mutable
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
import os
print(os.path.commonprefix(["flower", "flow", "flight"]))
flow
flo
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
from collections import Counter
s = "aabbcdc"
c = Counter(s)
print(next((ch for ch in s if c[ch] == 1), None))
b
None
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
print(" ".join("hello world".split()[::-1]))
world hello
olleh dlrow
hello world
dlrow olleh
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
s = "programming"
seen, first = set(), None
for c in s:
if c in seen:
first = c
break
seen.add(c)
print(first)
r
p
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
from collections import Counter
s = "swiss"
c = Counter(s)
print(next(ch for ch in s if c[ch] == 1))
i
w
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
def is_pal(s):
t = [c.lower() for c in s if c.isalnum()]
return t == t[::-1]
print(is_pal("A man, a plan, a canal: Panama"), is_pal("race a car"))
False False
True False
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
s = "abcabcbb"
seen, left, best = {}, 0, 0
for i, c in enumerate(s):
if c in seen and seen[c] >= left:
left = seen[c] + 1
seen[c] = i
best = max(best, i - left + 1)
print(best)
3
8
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
s = "aaabccdddd"
out, i = "", 0
while i < len(s):
j = i
while j < len(s) and s[j] == s[i]:
j += 1
out += s[i] + str(j - i)
i = j
print(out)
a3b1c2d4
3a1b2c4d
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
words = "the sky is blue".split()
print(" ".join(reversed(words)))
blue sky is the
the sky is blue
blue is sky the
eulb si yks eht
Sign up free to see the answer and a step-by-step explanation.
f
fl
d
a
g
m
None
s
False True
True True
4
2
a3bc2d4
abcd