Sponsored
Sponsored
This approach involves iterating through each name in the list, transforming the name so that the first letter is uppercase and the rest are lowercase. This is a common string manipulation problem that can be solved using built-in string functions in most programming languages.
Time Complexity: O(n) for each name, where n is the length of the name.
Space Complexity: O(1) since we modify the names in place.
1function formatNames(users) {
2 return users.map(([userId, name]) => [userId, name.charAt(0).toUpperCase() + name.slice(1).toLowerCase()]);
3}
4
5// Example usage
6const users = [[1, 'aLice'], [2, 'bOB']];
7const formattedUsers = formatNames(users);
8
9console.log("+---------+-------+");
10console.log("| user_id | name |");
11console.log("+---------+-------+");
12formattedUsers.forEach(([userId, name]) => {
13 console.log(`| ${userId} | ${name} |`);
14});
15console.log("+---------+-------+");
JavaScript uses charAt()
and slice()
to access and modify string parts. The functional approach with map()
allows us to apply the transformation to each element in the array.
This approach applies regular expressions to locate patterns that match the criteria and replace them with the desired format. This leverages the pattern matching capability of regex to achieve the transformation in fewer lines of code.
Time Complexity: O(n) for each name due to regex matching and replacement, where n is the length of the name.
Space Complexity: O(n) for storing the modified strings.
1function formatNames(users) {
2 return
JavaScript's replace
function, allied with capturing groups in the regex ^(\w)(\w*)
, helps modify the string efficiently. This approach makes it easier to manage complex string manipulation tasks.