Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8570491
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T18:34:14+00:00 2026-06-11T18:34:14+00:00

The problem runs as follows: if there are two strings str1 and str2 ,

  • 0

The problem runs as follows: if there are two strings str1 and str2, and another string str3, write a function which checks whether str3 contains both str1‘s letters and str2‘s letters in the same sequence as they were in the original sequences, though they may be interleaved. So, adbfec returns true for substrings adf and bec. I have written the following function in Python:

def isinter(str1,str2,str3):
    p1,p2,p3 = 0,0,0
    while p3 < len(str3):
        if p1 < len(str1) and str3[p3] == str1[p1]:
            p1 += 1
        elif p2 < len(str2) and str3[p3] == str2[p2]:
            p2 += 1
        else:
            break
        p3 = p1+p2
    return p3 == len(str3)

There is another version of this program, at ardentart (the last solution). Now which one is better? I think mine, for it probably does it in linear time. Whether it is better or not, is there any further room for optimization in my algo?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T18:34:15+00:00Added an answer on June 11, 2026 at 6:34 pm

    You could split all three strings in lists:

    list1 = list(str1)
    

    and then walk list3 with the same algorithm you use now, checking whether list3[i] is equal to list1[0] or list2[0]. If it was, you’d del the item from the appropriate list.

    Premature list end could then be caught as an exception.

    The algorithm would be exactly the same, but implementation ought to be more performant.

    UPDATE: turns out it actually isn’t (about double the time). Oh well, might be useful to know.

    And while benchmarking different scenarios, it turned out that unless it is specified that the three string lengths are “exact” (i.e., len(p1)+len(p2) == len(p3) ), then the most effective optimization is to check first thing. This immediately discards all cases where the two input strings can’t match the third because of bad string lengths.

    Then I encountered some cases where the same letter is in both strings, and assigning it to list1 or list2 might lead to one of the strings no longer matching. In those cases the algorithm fails with a false negative, which would require a recursion.

    def isinter(str1,str2,str3,check=True):
        # print "Checking %s %s and %s" % (str1, str2, str3)
        p1,p2,p3 = 0,0,0
        if check:
            if len(str1)+len(str2) != len(str3):
                return False
        while p3 < len(str3):
            if p1 < len(str1) and str3[p3] == str1[p1]:
                if p2 < len(str2) and str3[p3] == str2[p2]:
                    # does str3[p3] belong to str1 or str2?
                    if True == isinter(str1[p1+1:], str2[p2:], str3[p3+1:], False):
                       return True
                    if True == isinter(str1[p1:], str2[p2+1:], str3[p3+1:], False):
                       return True
                    return False
                p1 += 1
            elif p2 < len(str2) and str3[p3] == str2[p2]:
                p2 += 1
            else:
                return False
            p3 += 1
        return p1 == len(str1) and p2 == len(str2) and p3 == len(str3)
    

    Then I ran some benchmarks on random strings, this the instrumentation (notice that it generates always valid shuffles, which may yield biased results):

    for j in range(3, 50):
            str1 = ''
            str2 = ''
            for k in range(1, j):
                    if random.choice([True, False]):
                            str1 += chr(random.randint(97, 122))
                    if random.choice([True, False]):
                            str2 += chr(random.randint(97, 122))
            p1 = 0
            p2 = 0
            str3 = ''
            while len(str3) < len(str1)+len(str2):
                    if p1 < len(str1) and random.choice([True, False]):
                            str3 += str1[p1]
                            p1 += 1
                    if p2 < len(str2) and random.choice([True, False]):
                            str3 += str2[p2]
                            p2 += 1
            a = time.time()
            for i in range(1000000):
                    isShuffle2(str1, str2, str3)
            a = (time.time() - a)
            b = time.time()
            for i in range(1000000):
                    isinter(str1, str2, str3)
            b = (time.time() - b)
    
            print "(%s,%s = %s) in %f against %f us" % (str1, str2, str3, a, b)
    

    The results seem to point to a superior efficiency of the cached+DP algorithm for short strings. When strings get longer (more than 3-4 characters), the cache+DP algorithm starts losing ground. At around length 10, the algorithm above performs twice as fast as the totally-recursive, cached version.

    The DP algorithm performs better, but still worse than the above one, if strings contain repeated characters (I did this by restricting the range from a-z to a-i) and if the overlap is slight. For example in this case the DP loses by only 2us:

    (cfccha,ddehhg = cfcchaddehhg) in 68.139601 against 66.826320 us
    

    Not surprisingly, full overlap (one letter from each string in turn) sees the larger difference, with a ratio as high as 364:178 (a bit more than 2:1).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a windows-form which runs without any problem and displayed well. But if
Maddening problem here. When my page loads: <body onload=getClientDateTime();> It runs this function: document.getElementById('ClientDateTime').value=hello
Greetings, I have to following problem. I have a WCF Service which runs under
I was following this tutorial: http://www.vogella.com/articles/AndroidLocationAPI/article.html --> Paragraph 6.0 Problem: My emulator runs perfectly
I'm having a problem wherein my Python 2.7.3rc2 code runs fine through an IDE
I experience a weird problem; I have a bash script that runs as wwwrun,
We're having a problem with a merge replication. Our publisher runs SQL Server 2008,
This is a very weird problem. My app that runs just fine but somehow
I'm using IE8 and webdriver. The problem I have is every time webdriver runs
Problem String concatenation is slowing down a query: date(extract(YEAR FROM m.taken)||'-1-1') d1, date(extract(YEAR FROM

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.