The Wayback Machine - https://web.archive.org/web/20240927120052/https://www.geeksforgeeks.org/using-ordereddict-python-check-order-characters-string/
Open In App

Python | Check order of character in string using OrderedDict( )

Last Updated : 27 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples:

Input: 
string = "engineers rock"
pattern = "er";
Output: true
Explanation:
All 'e' in the input string are before all 'r'.

Input:
string = "engineers rock"
pattern = "gsr";
Output: false
Explanation:
There are one 'r' before 's' in the input string.

We have existing solution for this problem, please refer Check if string follows order of characters defined by a pattern or not | Set 1. Here we solve this problem quickly in python using OrderedDict(). Approach is very simple,

  • Create an OrderedDict of input string which contains characters of input strings as Key only.
  • Now set a pointer at the start of pattern string.
  • Now traverse generated OrderedDict and match keys with individual character of pattern string, if key and character matches with each other then increment pointer by 1.
  • If pointer of pattern reaches it’s end that means string follows order of characters defined by a pattern otherwise not.

Python3




# Function to check if string follows order of
# characters defined by a pattern
from collections import OrderedDict
 
def checkOrder(input, pattern):
     
    # create empty OrderedDict
    # output will be like {'a': None,'b': None, 'c': None}
    dict = OrderedDict.fromkeys(input)
 
    # traverse generated OrderedDict parallel with
    # pattern string to check if order of characters
    # are same or not
    ptrlen = 0
    for key,value in dict.items():
        if (key == pattern[ptrlen]):
            ptrlen = ptrlen + 1
         
        # check if we have traverse complete
        # pattern string
        if (ptrlen == (len(pattern))):
            return 'true'
 
    # if we come out from for loop that means
    # order was mismatched
    return 'false'
 
# Driver program
if __name__ == "__main__":
    input = 'engineers rock'
    pattern = 'er'
    print (checkOrder(input,pattern))


Output:

true

Check order of character in string Using two pointers

This Approach checks if the characters in the given pattern appear in the same order in the given string. It uses two pointers to keep track of the positions of the characters being compared. If all the characters in the pattern are found in the same order in the string, the function returns True, otherwise False.

Algorithm

1. Initialize two pointers, one for the string and one for the pattern, both starting at 0.
2. Traverse through the string character by character.
3. If the current character in the string matches the current character in the pattern, increment the pattern pointer.
4. Increment the string pointer after processing each character.
5. If the pattern pointer is equal to the length of the pattern, return True.
6. If the end of the string is reached and the pattern pointer is less than the length of the pattern, return False.

Python3




def check_order(string, pattern):
    i, j = 0, 0
    for char in string:
        if char == pattern[j]:
            j += 1
        if j == len(pattern):
            return True
        i += 1
 
    return False
string = 'engineers rock'
pattern = 'er'
print(check_order(string, pattern))


Output

True

Time Complexity: O(n), where n is length of string
Space Complexity: O(1)



Previous Article
Next Article

Similar Reads

K’th Non-repeating Character in Python using List Comprehension and OrderedDict
Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: Input : str = geeksforgeeks, k = 3 Output : r First non-repeating character is f, second is o and t
2 min read
LRU Cache in Python using OrderedDict
LRU (Least Recently Used) Cache discards the least recently used items first. This algorithm requires keeping track of what was used when, which is expensive if one wants to make sure the algorithm always discards the least recently used item. General implementations of this technique require keeping "age bits" for cache-lines and track the "Least
4 min read
How to iterate over OrderedDict in Python?
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. Explanation: Input : original_dict = { 'a':1, 'b':2, 'c':
2 min read
OrderedDict in Python
An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python. OrderedDict vs dict in Python`OrderedDict` maintains the sequence in which keys are added, ensuring that the order is preserved during iteration. In c
10 min read
How to convert JSON to Ordereddict?
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-
2 min read
How to convert a nested OrderedDict to dict?
In this article, we will discuss how to convert a nested OrderedDict to dict? Before this we must go through some concepts: Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value i
3 min read
How to convert Ordereddict to JSON?
In this article, we will learn How to convert a nested OrderedDict to JSON? Before this we must go through some concepts: The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in packa
3 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Count of index pairs (i, j) such that string after deleting ith character is equal to string after deleting jth character
Given a string str of N characters, the task is to calculate the count of valid unordered pairs of (i, j) such that the string after deleting ith character is equal to the string after deleting the jth character. Examples: Input: str = "aabb"Output: 2Explanation: The string after deletion of 1st element is "abb" and the string after deletion of 2nd
6 min read
Check input character is alphabet, digit or special character
All characters whether alphabet, digit or special character have ASCII value. Input character from the user will determine if it's Alphabet, Number or Special character.ASCII value ranges- For capital alphabets 65 - 90For small alphabets 97 - 122For digits 48 - 57 Examples : Input : 8 Output : Digit Input : E Output : Alphabet C/C++ Code // CPP pro
3 min read
Check whether the given character is in upper case, lower case or non alphabetic character
Given a character, the task is to check whether the given character is in upper case, lower case, or non-alphabetic character Examples: Input: ch = 'A'Output: A is an UpperCase characterInput: ch = 'a'Output: a is an LowerCase characterInput: ch = '0'Output: 0 is not an alphabetic characterApproach: The key to solving this problem lies in the ASCII
11 min read
Last remaining character after repeated removal of the first character and flipping of characters of a Binary String
Given a Binary string str of length N, the task is to find the last character removed from the string by repeatedly removing the first character of the string and flipping all the characters of the string if the removed character is '0'. Examples: Input: str = "1001" Output: '0' Explanation: Removing str[0] from the string modifies str to "001". Re
5 min read
Replace every character of a string by a different character
Given a string str of lowercase alphabets only. The task is to replace every character by some new character. The new character belongs to [Tex]$a-z$ [/Tex](small case only) Replacement of str[i] is determined by: str[i] = Character obtained after traversing ascii(str[i]) no. of characters in 'a-z' repeatedly after str[i]. Examples: Input: str = "g
5 min read
Map every character of one string to another such that all occurrences are mapped to the same character
Given two strings s1 and s2, the task is to check if characters of the first string can be mapped with the character of the second string such that if a character ch1 is mapped with some character ch2 then all the occurrences of ch1 will only be mapped with ch2 for both the strings. Examples: Input: s1 = "axx", s2 = "cbc" Output: Yes 'a' in s1 can
8 min read
Count of substrings having the most frequent character in the string as first character
Given a string S consisting of lowercase alphabets of size N, the task is to count all substrings which contain the most frequent character in the string as the first character. Note: If more than one character has a maximum frequency, consider the lexicographically smallest among them. Examples: Input: S = "abcab"Output: 7Explanation:There are two
7 min read
Count substrings having frequency of a character exceeding that of another character in a string
Given a string S of size N consisting of characters a, b, and c only, the task is to find the number of substrings of the given string S such that the frequency of character a is greater than the frequency of character c. Examples: Input: S = "abcc"Output: 2Explanation:Below are all the possible substrings of S(= "abcc") having the frequency of the
15 min read
Kth character after replacing each character of String by its frequency exactly X times
Given a string S consisting of N digits from [1, 9] and a positive integer K and X. Every day each character of the string is replaced by its frequency and value. The task is to find the Kth character of the string after X days. Examples: Input: S = "1214", K = 10, X = 3Output: 4Explanation:1st day = "12214444"2nd day = “1222214444444444444444”3rd
8 min read
Modify the string such that every character gets replaced with the next character in the keyboard
Given a string str consisting of lowercase English alphabets. The task is to change each character of the string with the next letter (in a circular fashion) key in the keyboard. For example, 'a' gets replaced with 's', 'b' gets replaced with 'n', ....., 'l' gets replaced with 'z', ....., 'm' gets replaced with 'q'.Examples: Input: str = "geeks" Ou
4 min read
Find a string such that every character is lexicographically greater than its immediate next character
Given an integer N, the task is to find a string(considering only lowercase characters) of length (N+1) such that the character at any position should be lexicographically greater than its immediate next character. Examples: Input: 2 Output: cba c is greater than b and b is greater than a Input: 5 Output: fedcba Approach: Given an integer N, the ta
5 min read
Replace every character of string by character whose ASCII value is K times more than it
Given string str consisting of lowercase letters only and an integer k, the task is to replace every character of the given string with a character whose ASCII value is k times more than it. If the ASCII value exceeds 'z', then start checking from 'a in a cyclic manner. Examples: Input: str = "abc", k = 2 Output: cde Explanation: a is moved by 2 ti
9 min read
Sort an array of strings in ascending order with each string sorted in descending order
Given a array of strings S[] of size N (1 ? N ? 105), sort characters of each string in descending order and then print the array of strings in ascending order. Examples: Input: s[] = {"apple", "box", "cat"} Output: pplea tca xob Explanation: Sorting each string in descending order, S[] modifies to {"pplea", "xob", "tca"}. Sorting the array in asce
9 min read
Check if String can be generated by concatenating character or String itself
Given a target string S consisting of lowercase alphabets, the task is to make this string by performing some operation on an empty string such that: The first operation is to append a lower case alphabet to string S and The second operation is to append a copy of S to itself. Note: The first operation cannot be used continuously two times. Example
6 min read
Longest Common Prefix using Character by Character Matching
Given a set of strings, find the longest common prefix. Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed word by word matching algorithm in previous post.In this algorithm, instead
13 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
Generate string by incrementing character of given string by number present at corresponding index of second string
Given two strings S[] and N[] of the same size, the task is to update string S[] by adding the digit of string N[] of respective indices. Examples: Input: S = "sun", N = "966"Output: bat Input: S = "apple", N = "12580"Output: brute Approach: The idea is to traverse the string S[] from left to right. Get the ASCII value of string N[] and add it to t
4 min read
Check if a two character string can be made using given words
Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times. Examples: Input : str = "ya" words[] = {"ah", "oy", "to", "ha"} Output : YES We can j
6 min read
Count substrings that starts with character X and ends with character Y
Given a string str of n lowercase characters, the task is to count the number of substrings of str starting with character X and ending with character Y. Examples: Input: str = "abbcaceghcak" x = 'a', y = 'c' Output: 5 abbc, abbcac, ac, abbcaceghc, aceghc Input: str = "geeksforgeeks" x = 'g', y = 'e' Output: 6 Approach: Initialize two counters i.e.
6 min read
Shortest distance to every other character from given character
Given a string S and a character X where [Tex]X\varepsilon S[i] [/Tex], for some [Tex]0\leq i \leq S.length()-1 [/Tex]. The task is to return an array of distances representing the shortest distance from the character X to every other character in the string. Examples: Input: S = "geeksforgeeks", X = 'e' Output: [1, 0, 0, 1, 2, 3, 3, 2, 1, 0, 0, 1,
15 min read
Find the count of M character words which have at least one character repeated
Given two integers N and M, the task is count the total words of M character length formed by the given N distinct characters such that the words have at least one character repeated more than once. Examples: Input: N = 3, M = 2 Output: 3 Suppose the characters are {'a', 'b', 'c'} All 2 length words that can be formed with these characters are "aa"
4 min read
Article Tags :
Practice Tags :