Open In App

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

Last Updated : 27 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
Python - Insertion at the beginning in OrderedDict
Given an ordered dict, write a program to insert items in the beginning of the ordered dict. Examples: Input: original_dict = {'a':1, 'b':2} item to be inserted ('c', 3) Output: {'c':3, 'a':1, 'b':2}Input: original_dict = {'akshat':1, 'manjeet':2} item to be inserted ('nikhil', 3) Output: {'nikhil':3, 'akshat':1, 'manjeet':2} Below are various meth
2 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
8 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
Article Tags :
Practice Tags :