Problem overview
The method creatingIds receives a first name first and a last name last. The ID is the first 2 letters of first followed by the last 3 letters of last. Letters keep their case, and both names are English letters only.
For "John" and "Smith", the first two letters are Jo and the last three are ith, so the ID is "Joith". For "Jo" and "Doe" both names are used whole, giving "JoDoe". For "ada" and "Lovelace" the ID is "adace", with no case change.
Approach
This is two slices joined together. One slice counts from the start of a string, the other from the end. A slice text[start:end] includes start and stops before end, and either bound can be left out. A negative bound counts from the end of the string.
Step by step
- Take the first two letters of
firstwithfirst[:2]. With no start, the slice begins at index0, and it stops before index2, so it holds indexes0and1. - Take the last three letters of
lastwithlast[-3:]. The start-3is the third character from the end, and with no end the slice runs to the last character. - Join the slices with
+and return the result.
The solution in Python
class Solution:
def creatingIds(self, first: str, last: str) -> str:
return first[:2] + last[-3:]
Some details worth knowing:
- A negative start means the same thing for any length:
"Smith"[-3:]is"ith"and"Lovelace"[-3:]is"ace". You never need to computelen(last) - 3. - Slices are forgiving. If a string is shorter than the slice asks for, you get what exists instead of an error:
"ab"[-3:]is"ab"and"a"[:2]is"a". The constraints guarantee at least 2 and 3 letters, so this lesson never relies on it. - Both slices are new strings. The names passed in are not modified.
Slice or single index
The two ways of reading a string look alike, so it is worth seeing them side by side on "Smith":
"Smith"[-3]is"i": one character, the third from the end."Smith"[-3:]is"ith": that character and everything after it."John"[:1]is"J"and"John"[:3]is"Joh": the number after the colon is how many characters you keep when the slice starts at the front.
The colon is what turns an index into a slice. Without it you get one character, with it you get a piece of the string.
Edge cases and common mistakes
- Names of exactly the minimum length.
"Jo"and"Doe"give"JoDoe": the slices cover the whole names. - Off-by-one on the end index.
first[:1]keeps one letter andfirst[:3]keeps three. The end index is not included, so two letters need:2. - Using
last[-3]without the colon. That is a single character, the third from the end, not three letters."Smith"[-3]is"i". - Changing case. Don't capitalize anything.
"ada"stays"ad"at the front. - Swapping the names. The first name supplies the front of the ID and the last name supplies the end.
Testing
"John","Smith"gives"Joith"."Jo","Doe"gives"JoDoe"."ada","Lovelace"gives"adace"."Al","Lee"gives"AlLee".
