Skip to content

Conversation

@shuyinliu2011-svg
Copy link

@shuyinliu2011-svg shuyinliu2011-svg commented Oct 30, 2025

Print out empty string if there is no common prefix. I aim this to be counted towards the Hacktoberfest. Thank you!

Summary by Sourcery

Implement a Java command-line utility that finds and prints the longest common prefix among given string arguments, defaulting to an empty string when there are no inputs or no shared prefix.

New Features:

  • Add LongestCommonPrefix.java to compute and output the longest common prefix of command-line arguments, handling zero or single argument cases by printing an empty string or the lone argument.
  • Use iterative pairwise comparison with a helper method to build the common prefix across all inputs.

Summary by CodeRabbit

  • New Features
    • Added a command-line utility to compute the longest common prefix across multiple text inputs
    • Handles edge cases efficiently, including scenarios with no common prefix or single inputs

…y of strings. Print out empty string if there is no common prefix. I aim this to be counted towards the Hacktoberfest.
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 30, 2025

Reviewer's Guide

Introduces a standalone Java class that computes the longest common prefix of command-line arguments by handling edge cases, iteratively reducing the prefix across all inputs, and using a helper to compare two strings.

Class diagram for LongestCommonPrefix implementation

classDiagram
    class LongestCommonPrefix {
        +main(String[] args)
        -getCommonPrefix(String a, String b) String
    }
Loading

File-Level Changes

Change Details Files
Add main entry point with argument parsing and edge-case handling
  • Print introductory label
  • Return empty string when no arguments provided
  • Return sole argument when only one input
Java/LargestCommonPrefix.java
Iteratively reduce common prefix across multiple inputs
  • Loop through input array starting from second element
  • Update prefix by calling helper for each string
  • Exit early and print empty if prefix becomes empty
Java/LargestCommonPrefix.java
Implement helper to compute prefix of two strings
  • Compare characters up to the shorter string’s length
  • Append matching chars to StringBuilder
  • Stop on first mismatch and return accumulated prefix
Java/LargestCommonPrefix.java

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Oct 30, 2025

Walkthrough

A new Java program class is introduced that computes the longest common prefix from command-line arguments. It processes multiple strings iteratively by comparing them character by character, returning the shared prefix or an empty line if none exists.

Changes

Cohort / File(s) Summary
New LongestCommonPrefix Implementation
Java/LargestCommonPrefix.java
New file containing LongestCommonPrefix class with main(String[] args) entry point and private getCommonPrefix(String a, String b) helper method to compute the longest common prefix across provided arguments.

Sequence Diagram(s)

sequenceDiagram
    participant Main
    participant Args
    participant Logic
    participant Output
    
    Main->>Args: Read command-line arguments
    
    rect rgb(200, 220, 255)
    Note over Logic: Process arguments
    alt No arguments
        Logic->>Output: Print empty line
    else Single argument
        Logic->>Output: Print argument
    else Multiple arguments
        Logic->>Logic: Initialize prefix = first argument
        loop For each remaining argument
            Logic->>Logic: Compute common prefix with current
            alt Prefix becomes empty
                Logic->>Output: Print empty line and exit
            else Continue
                Logic->>Logic: Update prefix
            end
        end
        Logic->>Output: Print final prefix
    end
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Review the character-by-character comparison logic in getCommonPrefix() to verify correctness
  • Verify edge cases: empty arguments list, single argument, empty strings within arguments
  • Check loop termination conditions and prefix update logic

Poem

🐰 A prefix so common, we seek it with care,
Through strings and through arguments floating in air,
Each character matched 'til the common one's found,
On this hoppy algorithm, we all can rely—

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "Add an implementation of finding the longest common prefix of an array of strings" directly and accurately describes the main change in the changeset. The title clearly summarizes the addition of a new Java class that implements the longest common prefix algorithm, which matches both the raw summary and the PR objectives. The title is specific, concise, and avoids vague or generic terms, making it clear to teammates reviewing the repository history what the core contribution is.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-merge-pro
Copy link

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
No audit logging: The new code performs operations without any auditing or logging of actions, but this
small CLI utility may not require audit trails.

Referred Code
public static void main(String[] args) {
    System.out.print("The common prefix is:");
    if (args.length == 0) {
        System.out.println("");
        return;
    }
    if (args.length == 1) {
        System.out.println(args[0]);
        return;
    }

    String prev = args[0];

    for (int i = 1; i < args.length; i++) {
        prev = getCommonPrefix(prev, args[i]);
        if (prev.isEmpty()) {
            System.out.println("");
            return;
        }
    }



 ... (clipped 15 lines)
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Minimal error handling: The program handles empty and single-argument cases but lacks handling for nulls and
provides minimal messages for incorrect usage typical for CLI tools.

Referred Code
System.out.print("The common prefix is:");
if (args.length == 0) {
    System.out.println("");
    return;
}
if (args.length == 1) {
    System.out.println(args[0]);
    return;
}

String prev = args[0];

for (int i = 1; i < args.length; i++) {
    prev = getCommonPrefix(prev, args[i]);
    if (prev.isEmpty()) {
        System.out.println("");
        return;
    }
}

System.out.println(prev);


 ... (clipped 1 lines)
Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
No input validation: Command-line arguments are processed without validation or constraints, which may be
acceptable for a simple local CLI but lacks explicit validation per the guideline.

Referred Code
public static void main(String[] args) {
    System.out.print("The common prefix is:");
    if (args.length == 0) {
        System.out.println("");
        return;
    }
    if (args.length == 1) {
        System.out.println(args[0]);
        return;
    }

    String prev = args[0];

    for (int i = 1; i < args.length; i++) {
        prev = getCommonPrefix(prev, args[i]);
        if (prev.isEmpty()) {
            System.out.println("");
            return;
        }
    }



 ... (clipped 2 lines)
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@qodo-merge-pro
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Refactor logic into a separate method

Refactor the prefix-finding logic from the main method into a new, dedicated
method to separate business logic from presentation logic.

Java/LargestCommonPrefix.java [6-28]

 public static void main(String[] args) {
-    System.out.print("The common prefix is:");
-    if (args.length == 0) {
-        System.out.println("");
-        return;
-    }
-    if (args.length == 1) {
-        System.out.println(args[0]);
-        return;
+    String prefix = findLongestCommonPrefix(args);
+    System.out.println("The common prefix is:" + prefix);
+}
+
+private static String findLongestCommonPrefix(String[] strs) {
+    if (strs.length == 0) {
+        return "";
     }
 
-    String prev = args[0];
-
-    for (int i = 1; i < args.length; i++) {
-        prev = getCommonPrefix(prev, args[i]);
-        if (prev.isEmpty()) {
-            System.out.println("");
-            return;
+    String prefix = strs[0];
+    for (int i = 1; i < strs.length; i++) {
+        prefix = getCommonPrefix(prefix, strs[i]);
+        if (prefix.isEmpty()) {
+            // No need to check further if the prefix is already empty.
+            break;
         }
     }
-
-    System.out.println(prev);
+    return prefix;
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly proposes refactoring the core logic into a separate method, which significantly improves code structure, reusability, and testability by separating concerns.

Medium
  • More

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
Java/LargestCommonPrefix.java (2)

8-11: Simplify empty output.

Use System.out.println() instead of System.out.println("") for clearer intent.

Apply this diff:

         if (args.length == 0) {
-            System.out.println("");
+            System.out.println();
             return;
         }

17-27: Algorithm implementation is sound.

The iterative approach correctly computes the longest common prefix, and the early exit when the prefix becomes empty is a good optimization.

Consider applying the same simplification to line 22 as suggested for line 9:

             if (prev.isEmpty()) {
-                System.out.println("");
+                System.out.println();
                 return;
             }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b8464e and 0ad4284.

📒 Files selected for processing (1)
  • Java/LargestCommonPrefix.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (1)
Java/LargestCommonPrefix.java (1)

30-40: Helper method is well-implemented.

The character-by-character comparison correctly handles strings of different lengths and stops at the first mismatch. The logic is clear and correct.

* Problem : To find the longest common prefix string amongst an array of strings, input on command line.
* Explanation : Sample command -- java LongestCommonPrefix apple application appointment
*/
class LongestCommonPrefix {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Filename and class name mismatch.

The class is named LongestCommonPrefix but the file is named LargestCommonPrefix.java. In Java, the public class name must exactly match the filename, otherwise the code will not compile.

Rename the file to match the class name:

-Java/LargestCommonPrefix.java
+Java/LongestCommonPrefix.java

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In Java/LargestCommonPrefix.java around line 5, the declared class name
LongestCommonPrefix does not match the filename LargestCommonPrefix.java; update
one to match the other to fix the compilation error — either rename the file to
LongestCommonPrefix.java or rename the class to public class LargestCommonPrefix
(and update any references/imports accordingly) so the public class name exactly
matches the filename.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant