Problem overview
The method WordLengths receives a List<string> named words and returns a List<int> with the length of every word, in the same order. Each word produces exactly one number, so the result is as long as the input.
For ["I", "love", "pancakes"] the result is [1, 4, 8]. For ["banana", "kiwi", "fig"] it is [6, 4, 3]. A list with the single word "code" gives [4]. Uppercase and lowercase letters count the same: "Code" and "CODE" both have length 4.
Approach: transform every item
This is the "map" pattern: every input item becomes one output item. You don't skip anything and you don't combine items. The plan is to start with an empty result list, visit the words one by one, and add each word's length at the end of the result. Because both lists are filled from first to last, the lengths keep the order of the words.
The result holds integers, so its type is List<int>. A List<int> stores plain int values and is the type the method promises to return, so it can't be swapped for a list of strings.
Followed on the first example, lengths is empty at the start. After "I" it holds 1, after "love" it holds 1 and 4, and after "pancakes" it holds 1, 4 and 8. That is the list the method returns. Each pass through the loop does the same small job, which is why the body is a single line.
Step by step
- Create an empty
List<int>namedlengths. It starts empty because the numbers arrive one at a time. - Write a
foreachloop with astringnamedwordoverwords. Aforeachloop goes over aListjust as it goes over an array, and it runs once per word. - Add
word.LengthtolengthswithAdd.Lengthis the number of characters in the string. - Return
lengthsafter the loop. Returning inside the loop would end the method after the first word, and only one length would come back.
The solution in C#
class Solution {
public List<int> WordLengths(List<string> words) {
List<int> lengths = new List<int>();
foreach (string word in words) {
lengths.Add(word.Length);
}
return lengths;
}
}
Things to notice:
- A
stringhas aLengthproperty, with no parentheses. AListhasCountinstead, sowords.Countis the number of words andword.Lengthis the number of characters in one of them. Addappends at the end, which is what keeps the order.- The loop never changes
words. Changing a list while aforeachgoes over it throws an exception, but here onlylengthsgrows.
Edge cases and common mistakes
- Mixing up
LengthandCount.word.Countdoesn't compile for a plain string, andwords.Lengthdoesn't compile for aList. - Returning too early. Put the
returnafter the closing brace of the loop. - Counting the words instead of the letters. The result has one number for each word, and each number is that word's number of characters.
- An empty string. It has length 0, and the method adds a 0 for it. The lesson's inputs always have at least one word.
Testing
| words | Result |
|---|---|
["I", "love", "pancakes"] | [1, 4, 8] |
["banana", "kiwi", "fig"] | [6, 4, 3] |
["Code", "CODE", ""] | [4, 4, 0] |
