Data Structures: Anagram Problem Solution

HackerRank · Beginner ·⚡ Algorithms & Data Structures ·9y ago
Learn how to solve a problem making anagrams. This video is a part of HackerRank's Cracking The Coding Interview Tutorial with Gayle Laakmann McDowell. http://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview?utm_source=video&utm_medium=youtube&utm_campaign=ctci

What You'll Learn

The video demonstrates how to solve the anagram problem by creating a function that calculates the number of characters to remove from two strings to make them anagrams, using techniques such as character counting and delta calculation, implemented in Java.

Full Transcript

Hi, I'm Gail Lock McDow, author of Cracking the Coding Interview. Today I'm going to solve a problem called making anagrams. This problem goes as follows. You have two strings just with the lowercase characters A to Z. How many characters would you have to remove from the two strings to make them anagrams? So anagrams, as you might remember, are just permutations of a word. So rearrangements of the words. So for two words to be anagrams, it means that they have the same characters but just in different orders. So for example, you have the input hello and billion. You'd have to remove six characters total. The H and the E from hello and the B, I I N from billion. And then that will leave you with L, L, and O in each of the two strings. So given two arbitrary strings, how many characters would you have to remove from each string to make them anagrams? Well, anagrams are mean that they have the same exact characters and the same number of each characters. So without the order mattering. So if you want to know, you know, if you want, you have just the string a a and a and you want to make those two things anagrams of each other, you'd have to remove two a's from the first string. So if we have a whole bunch of characters, it's the same process essentially. If we want to make two strings anagrams each other, count how many times each character appears in each string and then look at the difference between those values. So let's turn to the code now. So I already have a main function written um that handles my input. So now I just need to write this function. Okay, what this what the logic here is going to be is just count how many times each character appears. So I'm going to and then get the del delta between these. So int char count one um is going to be I'll just push this off another function. I'm not going to write it right now. Um, get char counts of first. Then I do basically the same thing for the second string. And then I return the delta between these. Okay. So note here that I've been pretty aggressive with modularization. That's kind of a good thing to do in order to show great coding style. Okay, now let's turn to how getchar works. Get char counts works. So that's going to take in a string. I'll just call it s. And it's going to create. So it's going to need an array that with one slot for each letter. So I'm going to call this char counts. And it's going to be a size number of letters. And then it's going to go through each string, each character. Um, so for into i equals zero, i less than s.length oops i ++ char c equals um s.char i and then I need to convert like a to zero, b to one, c to two, etc. So one way of doing that is I get the offset. So I can take the character A and convert that to its ASKI code. Um then the character B will be the next integer. So in Java we can kind of treat integers treat characters sort of as integers. And so giving doing this we'll get the character value of A. So if I do B minus A, I'd actually get one. So the code here is going to be this character C minus this offset. And then so that's going to give me like A to 0, B to 1, C to 2, etc. Then I just need to increment the value of that code and return that array. My final method is this get delta function and it's going to take in two strings or two arrays and compute the delta between each value. Um so I'll do some very basic error handling right now. Um, in ideal world I should probably, you know, create throw an exceptional that, but I'm just going to give it a negative one. So, the rays need to be the same length. Uh, okay. Now, I just need to walk through each value in the arrays and compute the absolute value of their differences. So math.absolute value of array of one of i minus array two of i and delta plus equals difference turn delta. Okay. Now let's see how this works. I'll run this. All right. We pass our test cases. That's fantastic. I'll try a slightly more advanced one. And it looks like we're doing great. So let's review how our code works. So we have this number needed function and it counts how many times the character appears in each string and then it walks through the two counts and compute the difference of it. So to get the number of characters in each string that's pretty easy. We just use a simple uh array will be sufficient here. If we had a bigger variety of strings um or characters, some other slightly different data set, we might want to use a hashmap instead. A simple integer array is sufficient here. And then we walk through and get the delta between each value in each array. Now, we need to know again that it's the same length. So that's, you know, this is a pretty straightforward problem. One tip that's useful in a lot of problems and it was useful here is to really define and think about what exactly does it take to make two things anagrams and the algorithm sort of follows from that explanation. So keep that in mind for your future problems. Good luck.
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from HackerRank · HackerRank · 15 of 60

1 HackerRank for Professors
HackerRank for Professors
HackerRank
2 Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
HackerRank
3 How to Leverage Data-Driven Insights to Improve Recruiting Results
How to Leverage Data-Driven Insights to Improve Recruiting Results
HackerRank
4 Hire Top Linux Talent and System Admins with SudoRank [Webinar]
Hire Top Linux Talent and System Admins with SudoRank [Webinar]
HackerRank
5 How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
HackerRank
6 Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
HackerRank
7 How to Use HackerRank's CodePair Tool [Tutorial]
How to Use HackerRank's CodePair Tool [Tutorial]
HackerRank
8 Find Linux Talent with SudoRank challenges [Tutorial]
Find Linux Talent with SudoRank challenges [Tutorial]
HackerRank
9 VMware's Mat Connot details his favorite new way to engage top programmers
VMware's Mat Connot details his favorite new way to engage top programmers
HackerRank
10 An Inside Look at Coinbase's Recruiting Strategy [webinar]
An Inside Look at Coinbase's Recruiting Strategy [webinar]
HackerRank
11 How Evernote Enhanced Their Tech Recruiting Process
How Evernote Enhanced Their Tech Recruiting Process
HackerRank
12 5 strategies for being a tech recruiting champion with HackerRank [Webinar]
5 strategies for being a tech recruiting champion with HackerRank [Webinar]
HackerRank
13 HackerRank Story - Lets make the world flat!
HackerRank Story - Lets make the world flat!
HackerRank
14 Data Structures: Hash Tables
Data Structures: Hash Tables
HackerRank
Data Structures: Anagram Problem Solution
Data Structures: Anagram Problem Solution
HackerRank
16 Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
HackerRank
17 Big O Notation
Big O Notation
HackerRank
18 Algorithms: Graph Search, DFS and BFS
Algorithms: Graph Search, DFS and BFS
HackerRank
19 Algorithms: Bit Manipulation
Algorithms: Bit Manipulation
HackerRank
20 Data Structures: Solve 'Find the Running Median' Using Heaps
Data Structures: Solve 'Find the Running Median' Using Heaps
HackerRank
21 Data Structures: Heaps
Data Structures: Heaps
HackerRank
22 Algorithms: Memoization and Dynamic Programming
Algorithms: Memoization and Dynamic Programming
HackerRank
23 Algorithms: Sort An Array with Comparator
Algorithms: Sort An Array with Comparator
HackerRank
24 Algorithms: Solve 'Coin Change' Using Memoization and DP
Algorithms: Solve 'Coin Change' Using Memoization and DP
HackerRank
25 Data Structures: Solve 'Contacts' Using Tries
Data Structures: Solve 'Contacts' Using Tries
HackerRank
26 Data Structures: Tries
Data Structures: Tries
HackerRank
27 Algorithms: Bubble Sort
Algorithms: Bubble Sort
HackerRank
28 Algorithms: Merge Sort
Algorithms: Merge Sort
HackerRank
29 Algorithms: Quicksort
Algorithms: Quicksort
HackerRank
30 Data Structures: Binary Search Tree
Data Structures: Binary Search Tree
HackerRank
31 Data Structures: Trees
Data Structures: Trees
HackerRank
32 Algorithms: Solve 'Shortest Reach' Using BFS
Algorithms: Solve 'Shortest Reach' Using BFS
HackerRank
33 Algorithms: Solve 'Connected Cells' Using DFS
Algorithms: Solve 'Connected Cells' Using DFS
HackerRank
34 Algorithms: Solve 'Recursive Staircase' Using Recursion
Algorithms: Solve 'Recursive Staircase' Using Recursion
HackerRank
35 Algorithms: Binary Search
Algorithms: Binary Search
HackerRank
36 Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
HackerRank
37 Data Structures: Linked Lists
Data Structures: Linked Lists
HackerRank
38 Data Structures: Cycles in a Linked List
Data Structures: Cycles in a Linked List
HackerRank
39 Data Structures: Stacks and Queues
Data Structures: Stacks and Queues
HackerRank
40 Data Structures: Queue With Two Stacks
Data Structures: Queue With Two Stacks
HackerRank
41 Data Structures: Balanced Parentheses in Expression
Data Structures: Balanced Parentheses in Expression
HackerRank
42 Algorithms: Recursion
Algorithms: Recursion
HackerRank
43 How to Hire for Your Startup [Collision Panel Video]
How to Hire for Your Startup [Collision Panel Video]
HackerRank
44 HackerRank main() San Francisco | November 8, 2018
HackerRank main() San Francisco | November 8, 2018
HackerRank
45 The Enterprise Playbook for Technical Hiring
The Enterprise Playbook for Technical Hiring
HackerRank
46 Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
HackerRank
47 Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
HackerRank
48 Building a Culture for Developer Innovation
Building a Culture for Developer Innovation
HackerRank
49 Developer Trends in 2020 and Beyond
Developer Trends in 2020 and Beyond
HackerRank
50 HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank
51 Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
HackerRank
52 Accelerating Developer Innovation at PhonePe with Rahul Chari
Accelerating Developer Innovation at PhonePe with Rahul Chari
HackerRank
53 The Future of Work for Developers
The Future of Work for Developers
HackerRank
54 Scaling AI from Proof of Concept to Production
Scaling AI from Proof of Concept to Production
HackerRank
55 The Secret Sauce to getting hired in Myntra’s Tech Team
The Secret Sauce to getting hired in Myntra’s Tech Team
HackerRank
56 Reimagining Money with Paypal
Reimagining Money with Paypal
HackerRank
57 Engineering Predictions for 2021 and Beyond! 🎬
Engineering Predictions for 2021 and Beyond! 🎬
HackerRank
58 Future-forward Tech & Careers with BNY Mellon
Future-forward Tech & Careers with BNY Mellon
HackerRank
59 How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
HackerRank
60 Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
HackerRank

This video teaches how to solve the anagram problem by calculating the number of characters to remove from two strings to make them anagrams, using Java. The solution involves character counting and delta calculation.

Key Takeaways
  1. Define the problem and understand what makes two strings anagrams
  2. Create a function to count character occurrences in each string
  3. Calculate the delta between the two character count arrays
  4. Implement the solution in Java
  5. Test the function with sample inputs
💡 To solve the anagram problem, it's essential to define and think about what exactly makes two strings anagrams, and the algorithm will follow from that explanation.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →