Convert Valid Snake Case to Lower Camel Case
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
# Convert Valid Snake Case to Lower Camel Case
Given a valid snake-case identifier, convert it to lower camel case.
The input consists of one or more lowercase ASCII words separated by single underscores. There is no leading underscore, trailing underscore, or pair of adjacent underscores. The output keeps the first word lowercase, removes each underscore, and capitalizes the first letter of every later word.
Implement:
```python
def solve(name: str) -> str:
...
```
## Constraints
- `1 <= len(name) <= 100_000`
- `name` matches `[a-z]+(?:_[a-z]+)*`
## Examples
```text
"foo_bar" -> "fooBar"
"already" -> "already"
"http_api_name" -> "httpApiName"
```
Overview: Convert a valid lowercase snake-case identifier to lower camel case. Remove separators, capitalize each later word's first letter, and support both single-word names and inputs up to one hundred thousand characters.
Read the full Google Software Engineer interview experience this question came from
Implement solve(name). The valid snake-case input contains lowercase ASCII words separated by single underscores. Keep the first word lowercase, remove underscores, and capitalize the first letter of each later word.
Constraints
- 1 <= len(name) <= 100,000
- name matches [a-z]+(?:_[a-z]+)*.
Examples
Input: ('a',)
Expected Output: 'a'
Explanation: Checks one or several valid snake-case words.
Input: ('already',)
Expected Output: 'already'
Explanation: Checks one or several valid snake-case words.
Hints
- An underscore signals that the next letter should be capitalized.
- The input validity guarantee removes empty-word edge cases.
Community answers
Answer by sourabh.19.cse
Easy Java code
public class Solution {
public String solve(String name) {
StringBuilder sb = new StringBuilder();
boolean shouldBeCapital = false;
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (ch == '_') {
shouldBeCapital = true;
} else {
if (shouldBeCapital) {
sb.append(Character.toUpperCase(ch));
shouldBeCapital = false; // <-- RESET FLAG HERE
} else {
sb.append(ch);
}
}
}
return sb.toString();
}
}
Answer by czar
#include
#include
class Solution {
public:
std::string solve(const std::string& name) {
std::istringstream ss(name);
std::string word;
bool first = true;
std::string ans;
while (std::getline(ss, word, '_')) {
if (first) {
ans += word;
first = false;
continue;
}
word[0] = (char) ((int)word[0] - 'a' + 'A');
ans += word;
}
return ans;
}
};