Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

1. Overview

In this tutorial, we’ll learn how to check if a string is a rotation of another string.

We’ll briefly discuss what string rotation is. Then, we’ll look at some algorithms to solve the problem with code insight and complexity analysis.

2. Introduction to String Rotation

Before digging into some solutions, let’s discuss string rotation and what we should test for the algorithm.

2.1. String and String Rotation

A string is a sequence of primitive characters, and in Java, it’s wrapped in a String class. Although two strings might be different objects, we can compare their internal characters and check, for example, whether they’re equal or contain common patterns.

A rotation of a string is a string that contains the same characters but in a different order. Specifically, one or more characters are shifted from the original position. For example, the string “cdab” is a rotation of “abcd”. This can be seen in two steps:

  • abcd -> dabc shifts the last d to the first position
  • dabc -> cdab shifts the last c to the first position

This is done by shifting from the right, but it could be done also from the left.

Notably, we can say that if two strings aren’t the same length, they can’t be one rotation of the other.

2.2. Variable Names

To demonstrate, we’ll always refer to the rotation as the potential string candidate to check whether it’s an actual rotation of an origin.

2.3. Unit Testing

We have only two cases to test whether a string is a rotation. Notably, a string is a rotation of itself. Therefore, we might also want to test that corner case.

3. Rotation Contained in Doubled String

We can naively think that if we double our origin string, at some point, it will contain a rotation. We can picture this intuitively:

Rotation Contained in Doubled String

3.1. Algorithm

The algorithm is straightforward:

boolean doubledOriginContainsRotation(String origin, String rotation) {
    if (origin.length() == rotation.length()) {
        return origin.concat(origin)
          .contains(rotation);
    }

    return false;
}

3.2. Code Insight

We concatenate the origin with itself, and we check if it contains the potential rotation:

return origin.concat(origin).contains(rotation);

Let’s look at the algorithm complexity:

  • Time Complexity: O(n*m) where n is the length of the concatenation and m is the length of the rotation
  • Space Complexity: O(n) proportional to the length of the strings

3.3. Unit Tests

Let’s test the rotation contained in the doubled origin string when the rotation is ok. We’ll also test when the origin is the exact string as the rotation:

@Test
void givenDoubledOrigin_whenCheckIfOriginContainsRotation_thenIsRotation() {
    assertTrue(doubledOriginContainsRotation("abcd", "cdab"));
    assertTrue(doubledOriginContainsRotation("abcd", "abcd"));
}

Let’s test when the rotation isn’t contained. We’ll also test when the rotation is a longer string than the origin:

@Test
void givenDoubledOrigin_whenCheckIfOriginContainsRotation_thenNoRotation() {
    assertFalse(doubledOriginContainsRotation("abcd", "bbbb"));
    assertFalse(doubledOriginContainsRotation("abcd", "abcde"));
}

4. Rotation From Common Start With Origin

We can use the previous approach and build a more detailed algorithm.

First, let’s collect all the indexes in the rotation of the starting character of the origin. Finally, we loop over the origin and compare the strings at shifted positions. Let’s picture these steps in more detail:

Rotation From Common Start With Origin

4.1. Algorithm

Once we know the common characters, we can check whether the strings continue to be equal:

boolean isRotationUsingCommonStartWithOrigin(String origin, String rotation) {
    if (origin.length() == rotation.length()) {
        List<Integer> indexes = IntStream.range(0, origin.length())
          .filter(i -> rotation.charAt(i) == origin.charAt(0))
          .boxed()
          .collect(Collectors.toList());

        for (int startingAt : indexes) {
            if (isRotation(startingAt, rotation, origin)) {
                return true;
            }
        }
    }

    return false;
}

boolean isRotation(int startingAt, String rotation, String origin) {
    for (int i = 0; i < origin.length(); i++) {
        if (rotation.charAt((startingAt + i) % origin.length()) != origin.charAt(i)) {
            return false;
        }
    }

    return true;
}

4.2. Code Insight

There are two main points to focus on. The first is where we collect the indexes:

List<Integer> indexes = IntStream.range(0, origin.length())
  .filter(i -> rotation.charAt(i) == origin.charAt(0))
  .boxed()
  .collect(Collectors.toList());

These are the positions in the rotation where we can find the starting character of the origin.

Then, we loop over the strings and check at shifted positions:

for (int i = 0; i < origin.length(); i++) {
    if (rotation.charAt((startingAt + i) % origin.length()) != origin.charAt(i)) {
        return false;
    }
}

Notably, we use the modulo (%) to return from the first index when we exceed the rotation length.

Let’s look at the algorithm complexity:

  • Time Complexity: O(n*m) where n is the length of the origin and m is the number of indexes found
  • Space Complexity: O(n)

4.3. Unit Tests

Let’s test when the rotation has common starting characters with the origin and the remaining part of the strings are equal:

@Test
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenIsRotation() {
    assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "cdab"));
    assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "abcd"));
}

Let’s test when the rotation has common starting characters, but it’s either too long, or the remaining part doesn’t match:

@Test
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenNoRotation() {
    assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "bbbb"));
    assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "abcde"));
}

5. Rotation Comparing Prefix and Suffix

If we find a common starting character of origin and rotation, we can also say that our strings will be equal before and after that matching point. For example, our origin string “abcd” has the common c at position 2 with “cdab”. However, prefixes and suffixes will need to be equal accordingly for the remaining portion of the strings:

Rotation Comparing Prefix and Suffix

5.1. Algorithm

Whenever we find a common character, we can then compare the prefix and suffix for those segments of characters remaining, inverting the origin and the rotation:

boolean isRotationUsingSuffixAndPrefix(String origin, String rotation) {
    if (origin.length() == rotation.length()) {
        return checkPrefixAndSuffix(origin, rotation);
    }

    return false;
}

boolean checkPrefixAndSuffix(String origin, String rotation) {
    if (origin.length() == rotation.length()) {
        for (int i = 0; i < origin.length(); i++) {
            if (origin.charAt(i) == rotation.charAt(0)) {
                if (checkRotationPrefixWithOriginSuffix(origin, rotation, i)) {
                    if (checkOriginPrefixWithRotationSuffix(origin, rotation, i)) {
                        return true;
                    }
                }
            }
        }
    }

    return false;
}

boolean checkRotationPrefixWithOriginSuffix(String origin, String rotation, int i) {
    return origin.substring(i)
      .equals(rotation.substring(0, origin.length() - i));
}

boolean checkOriginPrefixWithRotationSuffix(String origin, String rotation, int i) {
    return origin.substring(0, i)
      .equals(rotation.substring(origin.length() - i));
}

5.2. Code Insight

We have two checks to make. First, we compare the rotation prefix with the origin suffix:

return origin.substring(i)
  .equals(rotation.substring(0, origin.length() - i));

Then, we compare the rotation suffix with the origin prefix:

return origin.substring(0, i)
  .equals(rotation.substring(origin.length() - i));

Notably, these checks can be done in any order.

Let’s look at the algorithm complexity:

  • Time Complexity: O(n*n) comparing two strings of length n
  • Space Complexity: O(n)

5.3. Unit Tests

Let’s test when the rotation has equal suffix and prefix with the origin given a common character:

@Test
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenIsRotation() {
    assertTrue(isRotationUsingSuffixAndPrefix("abcd", "cdab"));
    assertTrue(isRotationUsingSuffixAndPrefix("abcd", "abcd"));
}

Let’s test when the rotation doesn’t have an equal suffix and prefix with the origin:

@Test
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenNoRotation() {
    assertFalse(isRotationUsingSuffixAndPrefix("abcd", "bbbb"));
    assertFalse(isRotationUsingSuffixAndPrefix("abcd", "abcde"));
}

6. Rotation Comparing Queue of Characters

Another view of the problem is imagining the two strings as queues. Then, we shift the top character of the rotation into the tail and compare the new queue with the origin. Let’s see a simple picture of the queues:

Rotation Comparing Queue of Characters

6.1. Algorithm

We create the two queues. Then, we shift from the top character to the bottom of the rotation while checking if it’s equal to the origin at every step.

boolean isRotationUsingQueue(String origin, String rotation) {
    if (origin.length() == rotation.length()) {
        return checkWithQueue(origin, rotation);
    }

    return false;
}

boolean checkWithQueue(String origin, String rotation) {
    if (origin.length() == rotation.length()) {
        Queue<Character> originQueue = getCharactersQueue(origin);

        Queue<Character> rotationQueue = getCharactersQueue(rotation);

        int k = rotation.length();
        while (k > 0 && null != rotationQueue.peek()) {
            k--;
            char ch = rotationQueue.peek();
            rotationQueue.remove();
            rotationQueue.add(ch);
            if (rotationQueue.equals(originQueue)) {
                return true;
            }
        }
    }

    return false;
}

Queue<Character> getCharactersQueue(String origin) {
    return origin.chars()
      .mapToObj(c -> (char) c)
      .collect(Collectors.toCollection(LinkedList::new));
}

6.2. Code Insight

After creating the queue, what is relevant is how we can assert that our strings are equal:

int k = rotation.length();
while (k > 0 && null != rotationQueue.peek()) {
    k--;
    char ch = rotationQueue.peek();
    rotationQueue.remove();
    rotationQueue.add(ch);
    if (rotationQueue.equals(originQueue)) {
        return true;
    }
}

Moving the top element of the queue to the bottom in constant time gives us a new shifted object to compare with the origin.

Let’s look at the algorithm complexity:

  • Time Complexity: O(n*n) worst-case where we loop over the whole queue while comparing with the origin
  • Space Complexity: O(n)

6.3. Unit Tests

Let’s test that using queues when shifting the rotation from the top to the tail will match the origin:

@Test
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenIsRotation() {
    assertTrue(isRotationUsingQueue("abcd", "cdab"));
    assertTrue(isRotationUsingQueue("abcd", "abcd"));
}

Let’s test using queues when they won’t be equal:

@Test
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenNoRotation() {
    assertFalse(isRotationUsingQueue("abcd", "bbbb"));
    assertFalse(isRotationUsingQueue("abcd", "abcde"));
}

7. Conclusion

In this article, we saw some algorithms to check whether a string is a rotation of another string. We saw how to search for common characters and assert equality using a doubled-origin string and the contains() string method. Similarly, we can use algorithms to check whether the remaining parts of the string match at shifted positions or using suffixes and prefixes. Finally, we also saw an example using queues and moving the peek to the tail of the rotation until it’s equal to the origin.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)