Problem overview
The method LongWords receives a string[] called words and an int called n. It returns a List<string> with the words that have more than n characters, in their original order. A word with exactly n characters is left out, and a word that appears twice is kept twice.
For words = ["apple", "kiwi", "banana", "fig"] and n = 4, the method returns apple and banana. The word kiwi has exactly 4 characters, so it fails the test, and fig has only 3. For ["hi", "to", "be"] and n = 3, no word is long enough and the result is an empty list.
Approach: collect the words that pass
This is a filter: look at each word once, keep it if it passes a test, skip it otherwise. You don't know in advance how many words will pass, so the result can't be an array of a fixed size. A List<string> starts empty and grows with Add, which suits the job.
Visiting the words from first to last and adding each passing word at the end of the list keeps the original order without any extra work.
Here is the first example in order. apple has 5 characters, more than 4, so it is added. kiwi has 4, which is not more than 4, so it is skipped. banana has 6 and is added, and fig has 3 and is skipped. The list ends as apple, banana. The length test reads the same for every word, so the loop body stays two lines long: a comparison and an Add.
Step by step
- Create an empty
List<string>namedresult. It holds the words that pass. - Write a
foreachloop with astringnamedwordoverwords. It gives each word one turn. - Test the length inside the loop with
word.Length > n. The operator is>and not>=, because a word of exactlyncharacters must be left out. - Add the word to
resultinside theif. - Return
resultafter the loop. If nothing passed, it is still an empty list, which is the right answer.
The solution in C#
class Solution {
public List<string> LongWords(string[] words, int n) {
List<string> result = new List<string>();
foreach (string word in words) {
if (word.Length > n) {
result.Add(word);
}
}
return result;
}
}
A few details are worth knowing:
- On a string,
Lengthis a property, so it is written without parentheses. An array also usesLength, while aListusesCount. foreachonly reads the array. It doesn't changewords, so the original is untouched.- The method returns
List<string>even though the input is an array. The two types are different, and aListis the one that can grow.
Edge cases and common mistakes
- The boundary. Using
>=would keepkiwiin the first example. The test is strictly longer. - Returning inside the loop. A
returnthere would stop at the first word that passes and give back only part of the answer. n = 0. Every word has at least one letter, so withn = 0every word is kept.- Nothing passes. The method returns an empty list, not
null.
Testing
| words | n | Result |
|---|---|---|
["apple", "kiwi", "banana", "fig"] | 4 | apple, banana |
["hi", "to", "be"] | 3 | empty list |
["go", "went", "gone", "went"] | 3 | went, gone, went |
["a", "bb"] | 0 | a, bb |
