
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Second String Can Be Formed from First String in Python
Suppose we have two strings s and t. We have to check whether t can be formed using characters of s or not.
So, if the input is like s = "owleh" t = "hello", then the output will be True.
To solve this, we will follow these steps −
- freq := a map containing all characters and their frequencies
- for i in range 0 to size of t - 1, do
- if freq[t[i]] is 0, then
- return False
- freq[t[i]] := freq[t[i]] - 1
- if freq[t[i]] is 0, then
- return True
Let us see the following implementation to get better understanding −
Example Code
from collections import defaultdict def solve(s, t): freq = defaultdict(int) for i in range(len(s)): freq[s[i]] += 1 for i in range(len(t)): if freq[t[i]] == 0: return False freq[t[i]] -= 1 return True s = "owhtlleh" t = "hello" print(solve(s, t))
Input
"apuuppa"
Output
True
Advertisements