
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Check whether second string can be formed from characters of 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
- Related Articles
- Remove all characters of first string from second JavaScript
- Check if a string can be formed from another string using given constraints in Python
- Check if given string can be formed by concatenating string elements of list in Python
- Program to check whether final string can be formed using other two strings or not in Python
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to count number of palindromes of size k can be formed from the given string characters in Python
- Check if characters of one string can be swapped to form other in Python
- C++ code to check phone number can be formed from numeric string
- Check whether given string can be generated after concatenating given strings in Python
- Program to check whether one string can be 1-to-1 mapped into another string in Python
- Program to check whether palindrome can be formed after deleting at most k characters or not in python
- Check whether we can form string2 by deleting some characters from string1 without reordering the characters of any string - JavaScript
- Check if characters of a given string can be rearranged to form a palindrome in Python
- JavaScript - Remove first n characters from string
- Removing first k characters from string in JavaScript

Advertisements