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

  • SEARCH
  • Home
  • 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 7944735
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T00:38:30+00:00 2026-06-04T00:38:30+00:00

What am i doing wrong here? Java code for computing prefix function. Two input

  • 0

What am i doing wrong here?

Java code for computing prefix function. Two input are right but the last one is wrong.

Here’s the pseudocode:

Pseudocode

Java code:

class Main {
// compute prefix function
    public static void main(String[] args) {
        String p = "422213422153342";
        String x = "ababbabbabbababbabb";
        String y = "ababaca";

        printOutput(p);

        printOutput(y);

        System.out.println();System.out.println();
        System.out.println("the prefix func below is wrong. I am not sure why.");
        System.out.print("answer should be: 0 0 1 2 0 1 2 0 1 2 0 1 2 3 4 5 6 7 8");

        printOutput(x);
    }

    static void printOutput(String P){
        System.out.println();System.out.println();
        System.out.print("p[i]: ");
        for(int i = 0; i < P.length(); i++)System.out.print(P.charAt(i) + " ");
        System.out.println();
        System.out.print("Pi[i]: ");
        compute_prefix_func(P);
    }
    public static void compute_prefix_func(String P){
        int m = P.length();
        int pi[] = new int[m];

        for(int i = 0; i < pi.length; i++){
            pi[i] = 0;
        }

        pi[0] = 0;

        int k = 0;

        for(int q = 2; q < m; q++){
            while(k > 0 && ( ((P.charAt(k) + "").equals(P.charAt(q) + "")) == false)){
                k = pi[k];
            }
            if ((P.charAt(k) + "").equals(P.charAt(q) + "")){
                k = k + 1;
            }
            pi[q] = k;
        }

        for(int i = 0; i < pi.length; i++){
        System.out.print(pi[i] + " ");
        }
    }
}
  • 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-04T00:38:33+00:00Added an answer on June 4, 2026 at 12:38 am

    Okay, let’s start off by making the code much easier to read. This:

    if ((P.charAt(k) + "").equals(P.charAt(q) + ""))
    

    can be simplified to:

    if (P.charAt(k) == P.charAt(q))
    

    … and you’ve done that in multiple places.

    Likewise here:

    int pi[] = new int[m];
    
    for(int i = 0; i < pi.length; i++){
        pi[i] = 0;
    }
    
    pi[0] = 0;
    

    … you don’t need the explicit initialization. Variables are 0-initialized by default. (It’s unclear why you’re then setting pi[0] again, although I note that if P.length() is 0, this will throw an exception.)

    Next is to remove the explicit comparison with false, instead just using ! so we have:

    while(k > 0 && P.charAt(k) != P.charAt(q))
    

    Finally, let’s restructure the code a bit to make it easier to follow, use more conventional names, and change int pi[] to the more idiomatic int[] pi:

    class Main {
        public static void main(String[] args) {
            String x = "ababbabbabbababbabb";
    
            int[] prefix = computePrefix(x);
    
            System.out.println("Prefix series for " + x);
            for (int p : prefix) {
                System.out.print(p + " ");
            }
            System.out.println();
        }
    
        public static int[] computePrefix(String input) {
            int[] pi = new int[input.length()];
    
            int k = 0;
            for(int q = 2; q < input.length(); q++) {            
                while (k > 0 && input.charAt(k) != input.charAt(q)) {
                    k = pi[k];
                }
                if (input.charAt(k) == input.charAt(q)) {
                    k = k + 1;
                }
                pi[q] = k;
            }
            return pi;
        }
    }
    

    That’s now much easier to follow, IMO.

    We can now look back to the pseudocode and see that it appears to be using 1-based indexing for both arrays and strings. That makes life slightly tricky. We could mimic that throughout the code, changing every array access and charAt call to just subtract 1.

    (I’ve extracted the common subexpression of P[q] to a variable target within the loop.)

    public static int[] computePrefix(String input) {
        int[] pi = new int[input.length()];
        int k = 0;
        for (int q = 2; q <= input.length(); q++) {
            char target = input.charAt(q - 1);
            while (k > 0 && input.charAt(k + 1 - 1) != target) {
                k = pi[k - 1];
            }
            if (input.charAt(k + 1 - 1) == target) {
                k++;
            }
            pi[q - 1] = k;
        }
        return pi;
    }
    

    That now gives your desired results, but it’s really ugly. We can shift q very easily, and remove the + 1 - 1 parts:

    public static int[] computePrefix(String input) {
        int[] pi = new int[input.length()];
        int k = 0;
        for (int q = 1; q < input.length(); q++) {
            char target = input.charAt(q);
            while (k > 0 && input.charAt(k) != target) {
                k = pi[k - 1];
            }
            if (input.charAt(k) == target) {
                k++;
            }
            pi[q] = k;
        }
        return pi;
    }
    

    It’s still not entirely pleasant, but I think it’s what you want. Make sure you understand why I had to make the changes I did.

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

Sidebar

Related Questions

What am I doing wrong here? Declare @starttimestamp datetime = getdate(); RAISERROR(N'Code not valid
I'm a java newbie but I'm not sure what I'm doing wrong. When I
I'm sure I'm doing something stupid here, but the following code: ... public void
What am I doing wrong here folks? <?php include 'header.php'; /** * Display a
What am I doing wrong here? I'm trying to get started with jQuery UI
What am I doing wrong here: class Helo { // main: generate some simple
What am I doing wrong here? I'm serializing a value, storing it in a
What am I doing wrong here? private void SendMail(string from, string body) { string
What am I doing wrong here? Im trying to save a canvas drawing by
What am I doing wrong here? It says Database Count Failed (on the $count

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.