Write a Python function named first_recurring_character() or a JavaScript function named firstRecurringCharacter() that takes a string and returns either:
° The first recurring character in the given string, if one exists, or
° A null value like JavaScript’s or Kotlin’s null, Python’s None, or Swift’s nil.
Here’s the Swift version of my solution:
// Swift
func firstRecurringCharacter(text: String) -> String? {
var previouslyEncounteredCharacters = Set<Character>()
for character in text {
if previouslyEncounteredCharacters.contains(character) {
return String(character)
} else {
previouslyEncounteredCharacters.insert(character)
}
}
return nil
}
The Swift implementation differs from the Python and JavaScript versions due to Swift’s stricter typing
Swift’s Set requires you to specify the type of things that it will store. In this case, we want to store items of type Character.
When looping through the items in a string with a for loop in Swift, you get Character items. That’s why previouslyEncounteredCharacters stores Character items and not String items. Once the function detects the first recurring character, it converts that character into a string and returns that value.
Are you interviewing for job that involves coding or requires coding skills? Then it’s very likely that you’ll be asked to undergo a coding test in the interview.
A long while back, I very badly embarrassed myself in an interview with Google. A Googler friend referred me (referrals are always better than applying yourself) and a handful of days later, I was in the interview, and I did everything wrong. I promised myself that I would never embarrass myself with such a pitiful coding performance at an interview again, and I’d also like to help ensure that it never happens to you either.
The trick, of course, is to practice. In this series, How to solve coding interview questions, I’ll walk you through the sort of questions that you might be asked in a coding interview. Many of the questions you’ll be asked will involve the sort of things that get covered in a “Algorithms and data structures” class and will be designed to test your general problem-solving ability. I’ll show you a solution, and where applicable, I’ll show you some alternate solutions and discuss the pros and cons of each.
You should try coming up with your own answers before looking at mine — after all, it’s the best way to learn!
The “first recurring character” function
This is a classic coding interview question that is often presented to junior developers.
The challenge
Write a Python function named first_recurring_character() or a JavaScript function named firstRecurringCharacter() that takes a string and returns either:
The first recurring character in the given string, if one exists, or
A null value like JavaScript’s or Kotlin’s null, Python’s None, or Swift’s nil.
Here are some example inputs for first_recurring_character(), along with what their corresponding outputs should be:
If you give the function this input…
…it will produce this output:
'abcdeefg'
'e'
'abccddee'
'c'
'abcde'
null / None / nil
One solution
See if you can code it yourself, then scroll down for my solution.
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
If you had to perform the function’s job yourself, you’d probably go through the given string character by character and use a piece of paper to jot down the keep track of the characters you’ve already seen.
Here’s a solution that takes this approach, in Python:
def first_recurring_character(text):
previously_encountered_characters = []
for character in text:
if character in previously_encountered_characters:
return character
else:
previously_encountered_characters.append(character)
return None
Here’s the JavaScript version:
function firstRecurringCharacter(text) {
let previouslyEncounteredCharacters = []
for (const character of text) {
if (previouslyEncounteredCharacters.includes(character)) {
return character
} else {
previouslyEncounteredCharacters.push(character)
}
}
return null
}
Both do the following:
They use a built-in data structure to keep track of characters that they have previous encountered as they go through the given string character by character. In the Python version, the data structure is a list named previously_encountered_characters; in the JavaScript version, it’s an array named previouslyEncounteredCharacters.
The use a loop to go through the given string one character at a time.
For each character in the given string, the program checks to see if the current character has been encountered before:
If the current character has been encountered before, it’s the first repeated character. The function returns the current character.
If the current character has not been encountered before, it is added to the data structure of previously encountered characters.
If the function goes through the entire string without encountering a previously encountered character, it returns a null value (None in Python, null in JavaScript).
What’s the Big O?
If you’ve made it this far, you might be asked how you can improve the code. This is a different question in disguise: You’re actually being asked if you know the computational complexity or “The Big O” for your solution.
First, there’s the for loop. For a given string of length n, the worst-case scenario — either the string doesn’t have any recurring characters or the recurring character is at the very end — the loop will have to execute n times. That task’s complexity of O(n).
Next, let’s look inside the for loop. There’s a test to see if the current character is in the collection of previously encountered characters. In Python, this test is performed by the in operator; in JavaScript, it’s performed by the includes() method.
Python’s TimeComplexity page says that using the in operator to find an item in a list is an O(n) operation on average.
That’s because they both use the following algorithm to determine if a given item is in a list or array:
if we are not yet past the last item in the list/array:
get the next item in the list/array
if this item is the one we’re looking for:
return true
if we are at this point and we have not found the item:
return false
So the function is basically an O(n) operation performing an O(n) operation on average, effectively making it an O(n2) operation. As far as computational complexity goes, this is considered “horrible”:
Tap to view at full size.
Can you improve the code?
You’ve probably figured out that the way to improve the code is to try and reduce its time complexity.
You probably can’t reduce the time complexity of the for loop. The function has to find the first recurring character, which means that it needs to go through the characters in the given string in order, one at a time. This part of the function will be stuck at O(n).
But you might be able to reduce the time complexity of check to see if the current character in the loop has been encountered before. In the function’s current form, we’re using a Python list or JavaScript array to keep track of characters that we’ve encountered before. Looking up an item in in these structures is an O(n) operation on average.
The solution is to change the data structure that keeps track of previously encountered characters to one where looking for a specific item is faster than O(n). Luckily, both Python and JavaScript provide a data structure for sets, where the time to look up an item is generally O(1).
Let’s rewrite the function to use sets. Here’s the Python version:
def first_recurring_character(text):
previously_encountered_characters = set()
for character in text:
if character in previously_encountered_characters:
return character
else:
previously_encountered_characters.add(character)
return None
The Python version doesn’t require much changing. We simply changed the initial definition of previously_encountered_characters from an empty array literal ([]) to a set constructor and call on set’s add() method instead of the append() method for arrays.
Here’s the JavaScript version:
function firstRecurringCharacter(text) {
let previouslyEncounteredCharacters = new Set()
for (const character of text) {
if (previouslyEncounteredCharacters.has(character)) {
return character
} else {
previouslyEncounteredCharacters.add(character)
}
}
return null
}
The JavaScript version requires only a little more changing:
The initial definition for previouslyEncounteredCharacters was changed to a Set constructor.
We changed the array includes() method to the set has() function.
We also changed the array push() method to the set add() method.
Changing the data structure that stores the characters that we’ve encountered before reduces the complexity to O(n), which is much better.
Coming up next
In the next article in this series, we’ll tackle a slightly different problem: Can you write a function that returns the first non-recurring character in a string?
You should be a regular listener/viewer of the Arguing Agile podcast, a YouTube show hosted by Tampa Bay techies Brian Orlando and Om Patel that features local techies talking about software development, agility, and everything in between, completely unscripted and unrehearsed — just real conversations about real tech work. In the past year, they’ve published 66 episodes, the latest of which features…me!
In this episode, titled Personal Agility and the Great Resignation, we talk about doing work in the brave new world of post-2020 and discuss things such as:
The power of team-building ceremonies and exercises, and why they have to be meaningful and not just “doing team stuff for team stuff’s sake.”
In the past couple of months, I’ve had my first chances to meet with my team at Auth0 (Developer Marketing) after working with them for a year and a half — first at a small summit in Salt Lake City, and last week in London.
Earlier in your life, it’s much easier to work ultra-hard in the quest to advance your career, but you can’t do it for an extended period. This is the exact thing that generates mid-life crises, and physical and mental health issues.
We talk about my time at Microsoft where I was a Windows Phone Champion, Albert Shum’s design for its “Metro” UI, and Microsoft’s thinking during the Ballmer era: “The mobile platform is the desktop platform, but lamer.”
I was at a gathering of P2P people at Microsoft in 2001 that was attended by Tim O’Reilly and Dave Winer, where we were told that “IE6 will be the last browser, because the future is applets.”
A story from my time at Cory Doctorow’s startup where how I show how hard it is to predict the future.
The importance of communication when working remotely and keeping Conway’s Law in mind.
Strip away the technology, and a teacher from hundreds of years ago would still recognize a present-day classroom and the lecture format.
We share stories about learning by doing, with Om talking about his daughter at med school and me talking about a story about the Logo programming language, where children learned beyond what they were being taught.
Our first computers: I had an Apple //e and Om had a Spectrum ZX, two serious Generation X machines.
I learned how to program at a computer store that tolerated my hanging out: Batteries Included, in Toronto.
Learning new languages: Python and Lingo, and picking up new languages to get the job done. This may be the first time on the podcast series where the languages Lisp and Prolog get mentioned.
A question that Brian asks during interviews: “Tell me about a time in the last 18 months where you did something to update your skills.”
Software isn’t a what, it’s a how. If you make software for an industry or field, you’re not in the software industry, but the industry or field that you’re making the software for.
About not participating in what Scott Galloway calls “the menace economy”: “I want to earn fair profit for my effort, but I don’t want to do it by stepping on somebody’s neck.”
There’s so much traditional culture force behind the way work is done. Ebenezer Scrooge’s accounting office in A Christmas Carol isn’t all that different from its modern-day counterpart.
Om: “I like to see a sitcom called The Home Office.”
@laugh_track_nat: For those that work remote: What are the pros and cons?
@SayitAintSooph: Pros: sleeping in, showering on my own time, no traffic, peace and quiet, running errands in spare time, taking my life back, not being overly tied to my work
Cons: people making up articles about wanting to return to office
It’s the time of the year when the New York Times Magazine publishes its “Future of Work” issue, and this year’s edition features an article titled Tech Companies Face a Fresh Crisis: Hiring. It tells the story of the current tech job market from the recruiter’s point of view.
It also contains three things that you should learn if you’re on the job market…
#1: It’s a tech job-seeker’s market, and 20 times more so for cybersecurity.
The article reports the following unemployment numbers:
For the general economy — that is, all work in all industries — the unemployment rate, which has been trending downward over the past year, is about 4%.
If you limit the unemployment rate to tech workers — the article doesn’t specify what counts as “tech” — the unemployment rate is less than half of the general rate: 1.7%.
If your area of specialization is cybersecurity, the unemployment rate is about a tenth of that for tech: 0.2%.
#2: Be nice to tech recruiters; it’ll make you stand out.
In a world of remote work and (hopefully temporary) reduced in-person contact, having good relations with at least a handful of recruiters can extend your reach and bring new opportunities you wouldn’t otherwise have.
At the same time, I’ve seen that people tend to ignore recruiters as long as they have work, and come running to them once they need a job. As the article puts it:
Tech employees today tire of the attention from recruiters, the friendly hellos on LinkedIn, the cold calls (which Dyba does not make). “They think we’re like used-car salesmen,” Dyba said of her quarry. To be a recruiter in tech is to be an in-demand commodity for those companies doing the hiring but to feel like something of a nuisance — like an essential gear that emits a loud, irritating noise.
This tendency to treat recruiters transactionally won’t endear you to them, and doesn’t give them any incentive to stand up for you when you really need them.
Many recruiters who reach out to techies get answered with silence or one of those LinkedIn auto-replies:
Want to make an impression on a recruiter whose help you might need in the future? Reply to their message, even if it’s just to say “Hey, I’m happy where I am right now, but let’s stay in touch in case things change.”
Here’s something that’s worked for me: Go through your inbox and look for recruiters whose messages went unanswered and answer them. I’ve done this and emailed recruiters that I forgot to reply to. They often see no response at all, and they appreciate it when someone gets back to them.
There’s a lot of advice to hold off on answering questions about your salary expectations. There needs to be more advice about waiting to ask about how much the job will pay, if these excerpts from the article is any indicator:
“If you wouldn’t mind kind of talking me through your background, I would love to hear a little bit more about you and what you’ve been doing,” she said. The young man on the other end of the phone was lovely and polite, with a Master of Science degree in business analytics. Dyba [the recruiter featured in the story] was immediately charmed, if only because — unlike so many tech recruits — he didn’t start the conversation by asking, within the first six minutes, what the compensation was.
…
Another recruiter said that when she sends out mass blasts, she often gets back emails that say only three words: “Rate? Remote? Client?”
Having skills is only part of the game. Because life is a team sport, connections matter too!
Want to harness the power of friendship?
Then you’ll want to catch this online panel, State of The Tampa Tech Scene, where you’ll find me and other organizers behind Tampa’s influential startups and meetups talking about the current state of technology and the tech industry, as well as how you can get involved and grow your network. Find out more on the event’s Meetup page.
ACE provides training and paid experience by partnering people age 18 through 24 with local employer for paid apprenticeships in areas including:
Business administration
Coding
Cybersecurity
Digital marketing
This orientation will cover the details of the ACE program, show you how to apply, and give you a chance to ask questions. If you’re looking for work in fields that provide lots of opportunity, good pay, and great prospects for your future, you don’t want to miss this — make sure that you (or a young person whose future you care about) sign up for this event!