Regex Substitution - HackerRank Solution Python

Featured image

Regex Substitution - HackerRank is a problem from HackerRank in the domain Python subdomain Regex called Regex Substitution. It’s one of the medium-level problems of Python. We have to solve this problem in Python.

Problem Statement and Explanation

In this problem, we have to use regular expressions to substitute all && and || symbols with and and or respectively using re.sub() method.

Input Format

Output Format

Print the modified HTML code for each test case as a single line and the modified HTML code should be printed as it was received as input.

Regex Substitution Solution in Python

Explanation of Solution

Complexity of the Solution

Time complexity

The time complexity of the solution is O(n), where n is the number of lines of text. This is because the substitute_text_in_string() function is called n times, once for each line of text.

The re.sub() function takes O(m) time, where m is the length of the regular expression pattern.

In this case, the regular expression pattern is of length 8, so the re.sub() function takes O(8) time. Therefore, the overall time complexity of the solution is O(n + 8) = O(n).

Space complexity

The space complexity of the solution is O(n), where n is the number of lines of text.

This is because the substitute_text_in_string() function creates a new string with the && and || characters replaced. The new string is of length n, so the space complexity of the solution is O(n).

In conclusion, the time and space complexity of the solution are both O(n).

Test Case of the Regex Substitution

Regex Substitution