<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samar dhiman on Medium]]></title>
        <description><![CDATA[Stories by Samar dhiman on Medium]]></description>
        <link>https://medium.com/@samardhiman007?source=rss-a0f2603ab4fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HnuIjuwFjx3O3boAp0YcCg.jpeg</url>
            <title>Stories by Samar dhiman on Medium</title>
            <link>https://medium.com/@samardhiman007?source=rss-a0f2603ab4fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:11:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samardhiman007/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Hidden Power of equals() and hashCode()]]></title>
            <link>https://samardhiman007.medium.com/the-hidden-power-of-equals-and-hashcode-28d4756f05a8?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d4756f05a8</guid>
            <category><![CDATA[hashcode-java]]></category>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[equals]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 18:20:18 GMT</pubDate>
            <atom:updated>2026-02-23T18:20:18.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqG70Vj9gxX2AHg6tXIrgQ.jpeg" /></figure><h3>Why One Wrong Method Can Break Your Entire Application ?</h3><p>Most Java developers override equals() and hashCode() early in their careers—but very few truly understand their <strong>impact on application correctness, performance, and data integrity</strong>.</p><p>A poorly implemented equals() or hashCode() doesn’t just cause bugs.<br> It can silently corrupt collections, break caching, and introduce production issues that are <strong>extremely hard to debug</strong>.</p><p>In this article, we’ll uncover:</p><ul><li>How equals() and hashCode() actually work</li><li>Why must they always be overridden together</li><li>How a single mistake can break HashMap and HashSet</li><li>Best practices every Java developer must follow</li></ul><p>In Java, <strong>object equality is not about memory — it’s about meaning</strong>.</p><p>By default:</p><ul><li>equals() checks <strong>reference equality</strong></li><li>hashCode() is derived from the object’s memory address</li></ul><p>That’s fine for simple objects — but dangerous for <strong>domain objects</strong> like User, Employee, or Order.</p><p>Collections such as:</p><ul><li>HashMap</li><li>HashSet</li><li>ConcurrentHashMap</li></ul><p><strong>depend heavily</strong> on the correct implementations of both methods.</p><h3>The Contract You Must Never Break</h3><h3>equals() Contract</h3><ul><li>Reflexive: x.equals(x) must be true</li><li>Symmetric: x.equals(y) ⇔ y.equals(x)</li><li>Transitive: if x.equals(y) and y.equals(z) → x.equals(z)</li><li>Consistent: result should not change</li><li>x.equals(null) must return false</li></ul><h3>hashCode() Contract (CRITICAL)</h3><p><strong>If two objects are equal according to </strong><strong>equals(), they MUST return the same </strong><strong>hashCode().</strong></p><p>The reverse is NOT required.</p><p>Breaking this rule causes <strong>undefined behavior</strong> in hash-based collections.</p><h3>How HashMap Really Uses These Methods</h3><p>Understanding this is the key to mastering the topic.</p><h3>Internal Flow:</h3><ol><li>hashCode() is called to determine the <strong>bucket</strong></li><li>If multiple objects exist in the bucket:</li></ol><ul><li>equals() is used to find the exact match</li></ul><p>If hashCode() is wrong:</p><ul><li>The object goes into the wrong bucket</li><li>Retrieval fails — even if the object exists</li></ul><h3>Best Practices (Quick Checklist)</h3><p>✅ Always override equals() and hashCode() together<br> ✅ Use immutable fields<br> ✅ Use Objects.equals() and Objects.hash()<br> ✅ Keep logic simple and consistent<br> ✅ Write unit tests for equality</p><p>If this article helped you understand Java a little better, consider clapping 👏 and sharing it with your team.<br> Follow me for more deep dives into Java, Spring Boot, and real-world backend engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d4756f05a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to JWT Implementation in Spring Boot]]></title>
            <link>https://samardhiman007.medium.com/a-beginners-guide-to-jwt-implementation-in-spring-boot-2da4ab1f0c76?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2da4ab1f0c76</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 17:10:38 GMT</pubDate>
            <atom:updated>2025-01-10T17:10:38.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UjhufinoH5mzF_MH8g7C4w.jpeg" /></figure><p>Authentication and authorization are critical components of any modern web application. As systems scale and become more distributed, traditional session-based authentication often struggles to keep up. Enter <strong>JSON Web Tokens (JWT)</strong>, a stateless, compact, and secure way of handling authentication.</p><p>In this article, we’ll walk through the step-by-step implementation of JWT in a <strong>Spring Boot</strong> application. Whether you’re new to Spring Boot or exploring JWT for the first time, this guide is designed to be beginner-friendly, with clear explanations and practical code examples.</p><p>By the end of this tutorial, you’ll learn:</p><ul><li>The basics of JWT and why it’s a popular choice for authentication.</li><li>How to integrate JWT into your Spring Boot application.</li><li>Writing secure authentication and authorization flows using JWT.</li></ul><p>Let’s get started and bring JWT-based authentication to life in your project!</p><h3>Step 1: Set Up Your Spring Boot Project</h3><p>Create a Spring Boot project with the following dependencies:</p><ul><li>Spring Web</li><li>Spring Security</li><li>Spring Boot Starter Data JPA (optional, for user storage)</li><li>H2 Database (or any database you prefer)</li><li>jjwt (for JWT handling)</li></ul><p>You can use Spring Initializr to generate the project or add the dependencies manually to your</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>    &lt;version&gt;0.11.5&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>    &lt;version&gt;0.11.5&lt;/version&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>    &lt;version&gt;0.11.5&lt;/version&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p><strong>Step 2: Create a User Entity and Repository</strong></p><p>Here’s an example of a simple User entity and JPA repository:</p><pre>@Entity<br>public class User {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String username;<br>    private String password;<br><br>    // Getters and Setters<br>}<br><br>// Repository <br>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    Optional&lt;User&gt; findByUsername(String username);<br>}</pre><h3>Step 3: Configure JWT Utility Class</h3><p>Create a utility class to generate and validate JWTs.</p><pre>import io.jsonwebtoken.*;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Date;<br><br>@Component<br>public class JwtUtil {<br><br>    private static final String SECRET_KEY = &quot;mySecretKey&quot;;<br>    private static final long EXPIRATION_TIME = 86400000; // 1 day in milliseconds<br><br>    public String generateToken(String username) {<br>        return Jwts.builder()<br>                .setSubject(username)<br>                .setIssuedAt(new Date())<br>                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))<br>                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)<br>                .compact();<br>    }<br><br>    public String extractUsername(String token) {<br>        return Jwts.parser()<br>                .setSigningKey(SECRET_KEY)<br>                .parseClaimsJws(token)<br>                .getBody()<br>                .getSubject();<br>    }<br><br>    public boolean validateToken(String token, String username) {<br>        return extractUsername(token).equals(username) &amp;&amp; !isTokenExpired(token);<br>    }<br><br>    private boolean isTokenExpired(String token) {<br>        Date expiration = Jwts.parser()<br>                .setSigningKey(SECRET_KEY)<br>                .parseClaimsJws(token)<br>                .getBody()<br>                .getExpiration();<br>        return expiration.before(new Date());<br>    }<br>}</pre><h3><strong>Step 4: Configure Security</strong></h3><p>Set up a custom UserDetailsService to fetch user data and configure Spring Security to handle JWT-based authentication.</p><pre>@Service<br>public class CustomUserDetailsService implements UserDetailsService {<br><br>    @Autowired<br>    private UserRepository userRepository;<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>        User user = userRepository.findByUsername(username)<br>                .orElseThrow(() -&gt; new UsernameNotFoundException(&quot;User not found&quot;));<br>        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList&lt;&gt;());<br>    }<br>}</pre><h3><strong>Security Configuration</strong></h3><pre>@EnableWebSecurity<br>public class SecurityConfig extends WebSecurityConfigurerAdapter {<br><br>    @Autowired<br>    private CustomUserDetailsService userDetailsService;<br><br>    @Autowired<br>    private JwtUtil jwtUtil;<br><br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.csrf().disable()<br>            .authorizeRequests()<br>            .antMatchers(&quot;/authenticate&quot;).permitAll()<br>            .anyRequest().authenticated()<br>            .and()<br>            .addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtUtil))<br>            .addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtUtil, userDetailsService));<br>    }<br>}</pre><h3>Step 5: Create Authentication and Authorization Filters</h3><pre>public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {<br><br>    private AuthenticationManager authenticationManager;<br>    private JwtUtil jwtUtil;<br><br>    public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {<br>        this.authenticationManager = authenticationManager;<br>        this.jwtUtil = jwtUtil;<br>    }<br><br>    @Override<br>    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {<br>        try {<br>            LoginRequest loginRequest = new ObjectMapper().readValue(request.getInputStream(), LoginRequest.class);<br>            return authenticationManager.authenticate(<br>                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())<br>            );<br>        } catch (IOException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br><br>    @Override<br>    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,<br>                                            FilterChain chain, Authentication authResult) throws IOException {<br>        String username = ((User) authResult.getPrincipal()).getUsername();<br>        String token = jwtUtil.generateToken(username);<br>        response.addHeader(&quot;Authorization&quot;, &quot;Bearer &quot; + token);<br>    }<br>}</pre><h3>Authorization Filter</h3><pre>public class JwtAuthorizationFilter extends BasicAuthenticationFilter {<br><br>    private JwtUtil jwtUtil;<br>    private CustomUserDetailsService userDetailsService;<br><br>    public JwtAuthorizationFilter(AuthenticationManager authManager, JwtUtil jwtUtil, CustomUserDetailsService userDetailsService) {<br>        super(authManager);<br>        this.jwtUtil = jwtUtil;<br>        this.userDetailsService = userDetailsService;<br>    }<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)<br>            throws IOException, ServletException {<br>        String header = request.getHeader(&quot;Authorization&quot;);<br>        if (header == null || !header.startsWith(&quot;Bearer &quot;)) {<br>            chain.doFilter(request, response);<br>            return;<br>        }<br><br>        String token = header.substring(7);<br>        String username = jwtUtil.extractUsername(token);<br><br>        if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br>            UserDetails userDetails = userDetailsService.loadUserByUsername(username);<br>            if (jwtUtil.validateToken(token, userDetails.getUsername())) {<br>                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(<br>                        userDetails, null, userDetails.getAuthorities());<br>                SecurityContextHolder.getContext().setAuthentication(authentication);<br>            }<br>        }<br><br>        chain.doFilter(request, response);<br>    }<br>}</pre><h3>Step 6: Test the Application</h3><ul><li>Create a user in your database.</li><li>Call the /authenticate endpoint with the user&#39;s credentials to get a JWT.</li><li>Use the JWT in the Authorization header for other secured endpoints.</li></ul><p>Congrats! 🎉 You’ve implemented JWT authentication in your Spring Boot app. JWT simplifies stateless authentication and enhances security. Remember to protect your secret key, use HTTPS, and set proper token expiration.</p><p>Feel free to customize this implementation for your needs. Got questions or feedback? Drop a comment! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2da4ab1f0c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IMPETUS Interview Experience (Java) SDE-1]]></title>
            <link>https://samardhiman007.medium.com/impetus-interview-experience-java-sde-1-d4a7cfe8ae83?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a7cfe8ae83</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[impetus-referral]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[impetus]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 20:10:03 GMT</pubDate>
            <atom:updated>2024-12-03T20:10:03.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPUC73PoUgrBHXS22agdkw.jpeg" /></figure><p>Recently, I had the opportunity to interview with Impetus. Here’s a step-by-step breakdown of my experience, which might be helpful for those preparing for interviews in similar companies.</p><h3>Step 1: Referral and HR Call</h3><p>The process started when I applied through a referral. Shortly after, an HR representative reached out to me.</p><ul><li><strong>Details Discussed:</strong></li><li>Current CTC (Cost to Company)</li><li>Expected CTC</li><li>Notice Period</li></ul><p>Once these details were shared, HR scheduled my first round of interviews.</p><h3>Step 2: First Round Interview</h3><p>On the scheduled day, I joined the interview, which was conducted remotely. Here’s how the session unfolded:</p><h4>Introduction Phase</h4><p>The interviewer started by introducing himself. After that, he asked me to give a brief introduction about myself.</p><h3>Step 3: Java Technical Questions</h3><p>The interviewer then dived into core Java topics. Below are the key questions he asked:</p><p><strong>What is Synchronization in Java?</strong></p><ul><li>He wanted a detailed explanation of how synchronization works and its importance in multithreading.</li></ul><p><strong>What is Serialization in Java?</strong></p><ul><li>I explained the concept, including how objects are converted into byte streams for storage or transmission.</li></ul><p><strong>Contract Between </strong><strong>equals() and </strong><strong>hashCode() Methods</strong></p><ul><li>He asked about the relationship between these two methods and their importance in data structures like HashMap.</li></ul><p><strong>Internal Working of </strong><strong>hashMap()</strong></p><ul><li>This question required explaining how hashCode() it influences the efficiency of hash-based collections.</li></ul><p><strong>Stream API</strong></p><ul><li>Questions focused on map() and filter() methods, specifically:</li><li><strong>What kind of function is passed to </strong><strong>map() and </strong><strong>filter()?</strong></li><li><strong>Difference Between </strong><strong>map() and </strong><strong>flatMap()</strong></li></ul><p><strong>ConcurrentHashMap</strong></p><ul><li>He asked me to explain its internal working and how it differs from a regular HashMap.</li></ul><h3>SQL Queries</h3><p>The interviewer presented two SQL join queries for me to solve. This tested my understanding of relational databases and joins.</p><h3>Coding Challenge</h3><p>The next part of the interview involved a coding task:</p><p><strong>Problem:</strong> Reverse a String using recursion.<br>I walked through my approach, wrote the code, and explained the logic behind it.</p><h3>My Turn to Ask Questions</h3><p>Towards the end, the interviewer gave me a chance to ask any questions. I asked about:</p><ul><li>The team structure</li><li>Current projects</li><li>The technology stack being used</li></ul><p>Overall, it was a well-structured interview that tested both my theoretical knowledge and practical problem-solving skills. The process also gave me valuable insights into how Impetus conducts its interviews, which will help me in future interviews.</p><p>If you found this article helpful or are preparing for similar interviews, feel free to <strong>follow me</strong> for more insights, tips, and experiences related to tech interviews and professional growth. Stay tuned for more content! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a7cfe8ae83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using RabbitMQ with Spring Boot: A Comprehensive Guide.]]></title>
            <link>https://samardhiman007.medium.com/using-rabbitmq-with-spring-boot-a-comprehensive-guide-ebf4f87bdb4e?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf4f87bdb4e</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 20:07:31 GMT</pubDate>
            <atom:updated>2024-09-26T20:07:31.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*OFH26naycXQ7yYW2HHvgyQ.jpeg" /></figure><p>RabbitMQ is a robust message broker that allows applications to communicate asynchronously. It enables decoupling between microservices by providing reliable, scalable, and distributed communication. In this article, we’ll walk through how to integrate RabbitMQ with Spring Boot, which makes it even easier to use by providing abstraction layers and ready-to-use features. In today’s digital world, efficient and reliable message handling is critical for many applications. RabbitMQ, a popular message broker, stands out for its versatility, robustness, and ease of use. This guide provides a comprehensive introduction to RabbitMQ, explaining what it is, how it works, and how you can get started.</p><p><strong>Why RabbitMQ?</strong></p><p>RabbitMQ supports multiple messaging protocols and allows applications to exchange messages in a fault-tolerant and scalable manner. It can handle a wide range of use cases, from simple message queuing to complex routing, pub/sub systems, and more. Some of the key benefits include:</p><ul><li><strong>Asynchronous communication</strong>: Services don’t need to wait for each other’s responses.</li><li><strong>Decoupling</strong>: Allows independent scaling and updates of services.</li><li><strong>Reliability</strong>: Message acknowledgments and delivery guarantees.</li><li><strong>Scalability</strong>: Horizontal scaling through clustering and federation.</li></ul><p>In the world of microservices, integrating RabbitMQ with Spring Boot brings simplicity and robustness, allowing developers to build resilient systems without handling the low-level details of message brokering.</p><h3>Setting Up RabbitMQ in a Spring Boot Project</h3><h3>Step 1: Add the Dependencies</h3><p>To get started, add the following dependencies to your Spring Boot project’s pom.xml (Maven):</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>This will pull in the necessary libraries to integrate RabbitMQ with Spring Boot.</h3><h3>Step 2: Configure RabbitMQ</h3><p>Next, you’ll need to configure the connection to your RabbitMQ server. In your application.properties or application.yml, add the following configuration:</p><pre>spring.rabbitmq.host=localhost<br>spring.rabbitmq.port=5672<br>spring.rabbitmq.username=guest<br>spring.rabbitmq.password=guest</pre><p>This is the default configuration. You can replace these values with the actual RabbitMQ host and credentials.</p><h3>Step 3: Creating a Message Queue</h3><p>We need to define a message queue, exchange, and binding. RabbitMQ follows a producer-exchange-queue model. First, create a configuration class:</p><pre>import org.springframework.amqp.core.*;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class RabbitMQConfig {<br><br>    @Bean<br>    public Queue queue() {<br>        return new Queue(&quot;myQueue&quot;, false);<br>    }<br><br>    @Bean<br>    public TopicExchange exchange() {<br>        return new TopicExchange(&quot;myExchange&quot;);<br>    }<br><br>    @Bean<br>    public Binding binding(Queue queue, TopicExchange exchange) {<br>        return BindingBuilder.bind(queue).to(exchange).with(&quot;routing.key&quot;);<br>    }<br>}</pre><p>Here, we created a simple queue named myQueue, a topic exchange myExchange, and bound them with a routing key routing.key.</p><h3>Step 4: Sending Messages</h3><p>To send messages to RabbitMQ, you’ll need a message producer. Create a simple producer class that will send messages to the configured exchange:</p><pre>import org.springframework.amqp.rabbit.core.RabbitTemplate;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class RabbitMQProducer {<br><br>    @Autowired<br>    private RabbitTemplate rabbitTemplate;<br><br>    public void sendMessage(String message) {<br>        rabbitTemplate.convertAndSend(&quot;myExchange&quot;, &quot;routing.key&quot;, message);<br>        System.out.println(&quot;Message sent: &quot; + message);<br>    }<br>}</pre><p>In this example, we use the RabbitTemplate to send a message to the exchange myExchange with the routing key routing.key.</p><h3>Step 5: Receiving Messages</h3><p>Now, let’s set up a consumer to listen to the queue and process incoming messages:</p><pre>import org.springframework.amqp.rabbit.annotation.RabbitListener;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class RabbitMQConsumer {<br><br>    @RabbitListener(queues = &quot;myQueue&quot;)<br>    public void receiveMessage(String message) {<br>        System.out.println(&quot;Received message: &quot; + message);<br>    }<br>}</pre><p>By annotating a method with @RabbitListener, we tell Spring that this method should be triggered whenever a message is received on the myQueue.</p><h3>Step 6: Testing the Integration</h3><p>To test our setup, you can create a simple REST controller that triggers the message producer:</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.*;<br><br>@RestController<br>@RequestMapping(&quot;/rabbitmq&quot;)<br>public class RabbitMQController {<br><br>    @Autowired<br>    private RabbitMQProducer producer;<br><br>    @PostMapping(&quot;/send/{message}&quot;)<br>    public String sendMessage(@PathVariable String message) {<br>        producer.sendMessage(message);<br>        return &quot;Message sent: &quot; + message;<br>    }<br>}</pre><p>You can now start your Spring Boot application and send messages using a REST client like Postman or curl:</p><pre>curl -X POST http://localhost:8080/rabbitmq/send/HelloWorld</pre><h3>Step 7: Scaling RabbitMQ with Spring Boot</h3><p>When you need to scale RabbitMQ for production use, consider:</p><ol><li><strong>Cluster RabbitMQ</strong>: Running RabbitMQ in a cluster improves reliability and fault tolerance.</li><li><strong>Handling Failures</strong>: Configure message retries and dead-letter queues (DLQ) to handle failed message processing.</li><li><strong>Monitoring</strong>: Use RabbitMQ’s management UI or Prometheus to monitor queue performance and application health.</li></ol><h3>Step 8: Advanced Features</h3><p>RabbitMQ provides advanced features that you can leverage in a production environment:</p><ul><li><strong>Dead Letter Queues (DLQ)</strong>: Redirect unprocessed messages for later inspection or retry.</li><li><strong>TTL (Time to Live)</strong>: Set a message or queue expiration time to ensure stale messages are removed.</li><li><strong>Priority Queues</strong>: Ensure important messages are processed first.</li><li><strong>Delayed Messaging</strong>: Deliver messages after a delay.</li></ul><h3>Conclusion</h3><p>RabbitMQ, combined with Spring Boot, provides an easy-to-implement messaging solution that can scale with your application. It allows you to decouple services, process tasks asynchronously, and build resilient, fault-tolerant systems. By following the steps outlined in this guide, you’ll be able to send, receive, and process messages in no time.</p><p>If you’re building microservices or want to integrate messaging into your Spring Boot applications, RabbitMQ is a powerful tool to consider. Keep experimenting with its features to get the most out of it for your use cases.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf4f87bdb4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Profiles]]></title>
            <link>https://samardhiman007.medium.com/spring-boot-profiles-568dd1486ab8?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/568dd1486ab8</guid>
            <category><![CDATA[backend-developer]]></category>
            <category><![CDATA[spring-boot-profiles]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 19:25:19 GMT</pubDate>
            <atom:updated>2024-08-24T19:25:19.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*TI6YVz1YqRV3g850WJ7wug.png" /></figure><p>Hey Developers! Welcome to this guide on Spring Boot profiles, a key feature that helps developers easily manage environment-specific configurations. Whether you’re new to Spring Boot or a seasoned pro, you’ll find valuable insights here.</p><p>In the dynamic world of software development, applications often need to run in different environments — such as development, testing, staging, and production. Each of these environments requires specific configurations that are tailored to their unique requirements. Managing these configurations can be a complex task, but Spring Boot offers a powerful solution: <strong>profiles</strong>.</p><p>So let’s start…</p><p><strong>What profiles are in Spring Boot</strong>?</p><p>Spring Boot profiles provide a mechanism to segregate parts of your application’s configuration so that they are activated only in specific environments. This allows you to define separate configurations for different environments and activate them based on the current context. For example, you might have one profile for development, another for testing, and a third for production.</p><p>Using profiles, you can control everything from database connections to the properties that govern how your application behaves. This flexibility is essential in maintaining a clean and maintainable codebase, especially as applications grow in complexity.</p><h4>How to Define and Use Profiles?</h4><p>Spring Boot profiles can be defined in several ways:</p><ol><li><strong>In </strong><strong>application.properties or </strong><strong>application.yml files</strong>: You can define environment-specific configuration files by naming them with the following convention: application-{profile}.properties or application-{profile}.yml. For instance, you might have application-dev.properties for development and application-prod.properties for production.</li><li><strong>Using the </strong><strong>@Profile annotation</strong>: You can annotate beans with @Profile to indicate that they should only be instantiated when a specific profile is active. This is particularly useful when certain beans are only needed in specific environments.</li></ol><pre>@Bean<br>@Profile(&quot;dev&quot;)<br>public DataSource devDataSource() {<br>    return new HikariDataSource();<br>}<br><br>@Bean<br>@Profile(&quot;prod&quot;)<br>public DataSource prodDataSource() {<br>    return new JndiDataSource();<br>}</pre><p><strong>3. Activating Profiles</strong>: Profiles can be activated in various ways:</p><ul><li><strong>Via application properties</strong>: By setting the spring.profiles.active property in your application.properties or application.yml file.</li><li><strong>Via command-line arguments</strong>: By passing the --spring.profiles.active argument when running your application.</li><li><strong>Via environment variables</strong>: By setting the SPRING_PROFILES_ACTIVE environment variable.</li></ul><h4>Practical Example: Configuring Data Sources</h4><p>Let’s consider a practical example where you need to configure different data sources for development and production environments. In development, you might want to use an in-memory database like H2, while in production, you would use a more robust database like PostgreSQL.</p><p>Here’s how you can achieve this using Spring Boot profiles:</p><ol><li><strong>Define profile-specific properties</strong>:</li></ol><pre># application-dev.properties<br>spring.datasource.url=jdbc:h2:mem:testdb<br>spring.datasource.driverClassName=org.h2.Driver<br>spring.datasource.username=sa<br>spring.datasource.password=password</pre><pre># application-prod.properties<br>spring.datasource.url=jdbc:postgresql://localhost:5432/proddb<br>spring.datasource.driverClassName=org.postgresql.Driver<br>spring.datasource.username=admin<br>spring.datasource.password=securepassword</pre><p><strong>2. Activate the desired profile</strong>:</p><p>During development, you would activate the dev profile, either by setting it in the properties file or by passing it as a command-line argument:</p><pre>java -jar myapp.jar --spring.profiles.active=dev</pre><p>For production, you would switch to the prod profile:</p><pre>java -jar myapp.jar --spring.profiles.active=prod</pre><h4>Best Practices for Using Spring Boot Profiles</h4><ul><li><strong>Keep profiles consistent</strong>: Ensure that all necessary profiles are defined and properly configured. Missing profiles can lead to unexpected behavior, especially in production.</li><li><strong>Avoid hard-coding profiles</strong>: Instead of hard-coding profiles in your code, use environment variables or command-line arguments to activate profiles dynamically.</li><li><strong>Use default profiles wisely</strong>: Spring Boot allows you to specify a default profile by setting the spring.profiles.default property. This is useful for local development or testing environments where you may not want to specify a profile every time.</li><li><strong>Test profile-specific configurations</strong>: Make sure to test each profile-specific configuration to avoid issues when deploying to different environments.</li></ul><p>I hope this article helps you in better understanding of the topic. Please do like and share for such informative articles.</p><p>Let me know in the comments if there are any doubts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=568dd1486ab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Java Stream API]]></title>
            <link>https://samardhiman007.medium.com/java-stream-api-d77673375962?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d77673375962</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[stream-api]]></category>
            <category><![CDATA[advanced-java]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Wed, 22 May 2024 20:05:07 GMT</pubDate>
            <atom:updated>2024-05-22T20:10:02.389Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V2d2FaSVoH2Qb3epmUSnVQ.jpeg" /></figure><p>Today we are going to learn about some interesting concepts in Java i.e. <strong><em>Stream API</em></strong> which is considered the most important part of Java development as well as from an interview point of view.</p><p>So the first question that comes to every learner is what is the use of Stream API when we can do the same thing without <strong>Stream API?</strong></p><p>So the answer to this is because it offers a more readable, concise, and functional approach to data processing by allowing you to write declarative code that focuses on the “<em>what</em>” rather than the “<em>how</em>.” It simplifies common operations such as filtering, mapping, and reducing through method chaining, and it integrates seamlessly with lambda expressions, promoting a functional programming style.</p><p>Now let&#39;s jump into the types of operations we have in stream API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*FLg0g-V4Wf4MBnmSPFQ4wQ.png" /></figure><h3>Different Operations On Streams</h3><p>There are two types of Operations in Streams:</p><ol><li><em>Intermediate Operations</em></li><li><em>Terminate Operations</em></li></ol><p><strong><em>Intermediate Operations</em></strong> are the types of operations in which multiple methods are chained in a row.</p><h3>Important Intermediate Operations</h3><p>There are a few <em>Intermediate Operations</em> mentioned below:</p><h4>1. map()</h4><p>The <em>map </em>method is used to return a stream consisting of the results of applying the given function to the elements of this stream.</p><pre>List number = Arrays.asList(2,3,4,5);<br>List square = number.stream().map(x-&gt;x*x).collect(Collectors.toList());</pre><p>2. <strong>filter()<br></strong>The <em>filter </em>method is used to filter the stream based on the predicate passed as an argument.</p><pre>List number = Arrays.asList(2,3,4,5);<br>List square = number.stream().filter(x-&gt;x%2==0).collect(Collectors.toList());</pre><p>3. <strong>sorted()</strong></p><p>The <em>sorted </em>method is used to sort the stream of data.</p><pre>List number = Arrays.asList(2,3,4,5);<br>List square = number.stream().sorted().collect(Collectors.toList());</pre><h3>Terminal Operations</h3><p><em>Terminal Operations</em> are the type of Operations that return the result. These Operations are not processed further just return a final result value.</p><h3>Important Terminal Operations</h3><p>There are a few Terminal Operations mentioned below:</p><h4>1. collect()</h4><p>The <em>collect </em>method is used to return the result of the intermediate operations performed on the stream.</p><pre>List number = Arrays.asList(2,3,4,5,3);<br>Set square = number.stream().map(x-&gt;x*x).collect(Collectors.toSet());</pre><h4>2. forEach()</h4><p>The <em>forEach </em>method is used to iterate through every element of the stream.</p><pre>List number = Arrays.asList(2,3,4,5);<br>number.stream().map(x-&gt;x*x).forEach(y-&gt;System.out.println(y));</pre><h4>3. reduce()</h4><p>The <em>reduce </em>method is used to reduce the elements of a stream to a single value. The reduce method takes a <em>BinaryOperator</em> as a parameter.</p><pre>List number = Arrays.asList(2,3,4,5);<br>int even = number.stream().filter(x-&gt;x%2==0).reduce(0,(ans,i)-&gt; ans+i);</pre><p>So these are some important stream API operations that are widely used in <em>Java programming</em> and asked in most <em>Java interviews.</em></p><p>I hope this article helps you in better understanding of the topic. Please do like and share for such informative articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d77673375962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Google Interview Experience — SDE I]]></title>
            <link>https://samardhiman007.medium.com/my-google-interview-experience-sde-i-5797005f4c57?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5797005f4c57</guid>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[google-interview]]></category>
            <category><![CDATA[sde-1]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 18:57:42 GMT</pubDate>
            <atom:updated>2024-03-14T18:58:45.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Google Interview Experience- SDE 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPcn6gQ7DWbkSbltvG2krA.png" /></figure><h3>Round 1: Phone Screening 💻</h3><p>The journey began with a tough phone interview, where I had to solve a complex problem involving dynamic programming and trees. It was challenging, but it pushed me to think creatively and come up with new ideas. Even though it was difficult, I tackled it with enthusiasm, using what I knew about algorithms and data structures to find a strong solution.</p><h3>Round 2: Online Round 1 💪🏻</h3><p>the second round was a friendly chat that lasted an hour. The interviewer introduced themselves, and then it was my turn to do the same. Next, we looked at a problem on trees together through a shared screen. The task was to figure out if we could split a tree into two equal halves. After some thinking, I came up with a solution and talked it through with the interviewer. They were happy with my approach and asked me to write the code. Then, the question changed a bit, asking how I’d solve it if the tree wasn’t binary. After discussing it with the interviewer, I came up with another solution they liked. We also talked about how long the solution would take to run and wrapped up with any questions I had.</p><h3>Round 3: Online Round 2 🧑🏻‍💻</h3><p>A week later, I got a call saying I made it to the next round. This time, it was a 45-minute technical chat followed by 15 minutes of more general questions. We started with a quick introduction, then jumped straight into another tree problem. I managed to solve the first one, but the follow-up was trickier. I tried different approaches, but none seemed to satisfy the interviewer. After the technical part, we moved on to more casual questions about my experiences, like internships. I realized I wasn’t fully prepared for this part, especially since I hadn’t been coding much lately. Plus, I felt a bit nervous during this section.</p><h3>Interview FeedBack</h3><p>After 4–5 days, I received an email from the recruiter that they are not moving forward with my candidature.</p><p><strong>Some tips that would be helpful.</strong></p><p><em>If you are reading this, Best of luck for your Interviews!</em></p><p><em>Do keep in mind that you did not end up using Hints from the Interviewer, Write almost bug-free code, Have very Good communication &amp; maintain speed while writing your code.</em></p><p>I hope you found this article helpful! 😀</p><p><strong><em>Wishing you a joyful learning journey!!! 🤝</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5797005f4c57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Interview Experience with Paytm]]></title>
            <link>https://samardhiman007.medium.com/my-interview-experience-with-paytm-460ba4006fcb?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/460ba4006fcb</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[paytm]]></category>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 15:32:40 GMT</pubDate>
            <atom:updated>2023-12-14T15:32:40.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Uuj69x4V4BH9Ioba1vT5Q.png" /></figure><p>Round 1: Online Assessment (OA)</p><p>The journey began with an Online Assessment comprising 10 questions. Two of them were coding challenges, one at an easy level and the other at a medium difficulty. Additionally, there were 6 Data Structures and Algorithms Multiple Choice Questions (MCQs).</p><p>Round 2: Technical Interview 1</p><p><em>Interviewer’s Introduction and Self-Introduction:</em> The session kicked off with a friendly introduction from the interviewer, followed by the standard request to introduce myself. It set a positive tone for the conversation.</p><p><em>Coding Challenge:</em> The interviewer promptly moved to a coding challenge, providing a LeetCode link: <a href="https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/">https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/</a>. We discussed the approach, ensuring clarity and understanding. Once satisfied, I proceeded to code the solution. Thorough testing followed, with the interviewer then delving into questions about time complexity, probing my understanding of algorithmic efficiency.</p><p><em>Domain-Specific Questions:</em> The interview seamlessly transitioned into domain-specific inquiries. Topics ranged from Spring Boot — its functionality and the process to enable Jetty — to practicalities like the default port of Tomcat. The interviewer explored my knowledge of HTTP status codes and delved into the intricacies of REST APIs, including whether they are stateful or stateless.</p><p><em>Database Management System (DBMS) Questions:</em> The technical depth increased with questions about database management. The discussion encompassed indexing, its mechanisms, and the concept of sharding.</p><p><em>Closing Questions:</em> To wrap up, the interviewer allowed me to ask questions. This phase is not only a chance to gain more insights but also reflects your genuine interest in the position and the company.</p><p>Round 3: Second Technical Interview</p><p><em>Introduction:</em> The second technical round commenced with the customary introductions. The interviewer then outlined that this session would primarily focus on system design.</p><p><em>System Design Challenge:</em> The core of this interview was a hands-on system design challenge. The task was to conceptualize and articulate the design of a URL Shortener website. This required considerations for scalability, efficiency, and other crucial aspects of system architecture.</p><p>Sharing my Paytm interview experience has been a valuable exercise in reflecting on the depth and breadth of the assessment process. Each round presented unique challenges, spanning coding proficiency, domain-specific knowledge, and the practical application of system design principles. I eagerly anticipate the next steps in this process and am grateful for the opportunity to showcase my skills at such a renowned organization.</p><p><em>Stay tuned for more updates on my professional journey!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=460ba4006fcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Counting Sort]]></title>
            <link>https://samardhiman007.medium.com/counting-sort-734e804d07e9?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/734e804d07e9</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 08:55:14 GMT</pubDate>
            <atom:updated>2023-02-16T08:55:14.532Z</atom:updated>
            <content:encoded><![CDATA[<p>A sorting method based on keys inside a certain range is called a counting sort. It operates by counting the number of items with unique key values (a kind of hashing). The position of each element in the output sequence can then be determined by performing simple arithmetic operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*wO4yLXQcFKVU5pilv3pWHw.png" /></figure><p><strong><em>Below is the implementation of the above algorithm:</em></strong></p><pre>// C++ Program for counting sort<br>#include &lt;bits/stdc++.h&gt;<br>#include &lt;string.h&gt;<br>using namespace std;<br>#define RANGE 255<br><br><br>void countSort(char arr[])<br>{<br> char output[strlen(arr)];<br><br><br> int count[RANGE + 1], i;<br> memset(count, 0, sizeof(count));<br><br> <br> for (i = 0; arr[i]; ++i)<br>  ++count[arr[i]];<br><br> <br> for (i = 1; i &lt;= RANGE; ++i)<br>  count[i] += count[i - 1];<br><br><br> for (i = 0; arr[i]; ++i) {<br>  output[count[arr[i]] - 1] = arr[i];<br>  --count[arr[i]];<br> }<br><br> for (i = 0; arr[i]; ++i)<br>  arr[i] = output[i];<br>}<br><br>int main()<br>{<br> char arr[] = &quot;countingsort&quot;;<br><br> countSort(arr);<br><br> cout &lt;&lt; &quot;Sorted character array is &quot; &lt;&lt; arr;<br> return 0;<br>}<br></pre><p><strong><em>Time Complexity</em></strong></p><p>Worst case time — <em>O</em>(<em>n</em>)</p><p>Best case time — <em>O</em>(<em>n</em>)</p><p>Average case time — <em>O</em>(<em>n</em>)</p><p>Space — <em>O</em>(<em>n</em>)</p><p><strong><em>If you liked this article, don’t forget to leave a clap and follow!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=734e804d07e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heap Sort]]></title>
            <link>https://samardhiman007.medium.com/heap-sort-5a9e0dec6e41?source=rss-a0f2603ab4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a9e0dec6e41</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Samar dhiman]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 08:35:28 GMT</pubDate>
            <atom:updated>2023-02-16T08:35:28.785Z</atom:updated>
            <content:encoded><![CDATA[<p>A comparison-based sorting method based on the Binary Heap data structure is called heap sort. It is identical to the selection sort in which the minimum element is initially located and placed at the start. For the remaining components, follow the same procedure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIyasT7eGML7DVHMhCGLHg.png" /></figure><p><strong><em>Implementation of Heap Sort</em></strong></p><pre>// Heap Sort<br><br>#include &lt;iostream&gt;<br>using namespace std;<br><br><br>void heapify(int arr[], int N, int i)<br>{<br><br><br> int largest = i;<br><br> int l = 2 * i + 1;<br><br><br> int r = 2 * i + 2;<br><br><br> if (l &lt; N &amp;&amp; arr[l] &gt; arr[largest])<br>  largest = l;<br><br> <br> if (r &lt; N &amp;&amp; arr[r] &gt; arr[largest])<br>  largest = r;<br><br><br> if (largest != i) {<br>  swap(arr[i], arr[largest]);<br><br><br>  heapify(arr, N, largest);<br> }<br>}<br><br><br>void heapSort(int arr[], int N)<br>{<br><br><br> for (int i = N / 2 - 1; i &gt;= 0; i--)<br>  heapify(arr, N, i);<br><br><br> for (int i = N - 1; i &gt; 0; i--) {<br><br> <br>  swap(arr[0], arr[i]);<br><br>  heapify(arr, i, 0);<br> }<br>}<br><br><br>int main()<br>{<br> int arr[] = { 12, 11, 13, 5, 6, 7 };<br> int N = sizeof(arr) / sizeof(arr[0]);<br><br><br> heapSort(arr, N);<br><br> cout &lt;&lt; &quot;Sorted array is \n&quot;;<br>  for (int i = 0; i &lt; N; ++i)<br>  cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br> cout &lt;&lt; &quot;\n&quot;;<br><br>}</pre><p>Time Complexity</p><ul><li>Worst case time complexity — O(n(log(n)) [all elements in the list are distinct]</li><li>Best case time complexity — O(n) [all elements are same]</li><li>Average case time complexity — O(n(log(n))</li><li>Space complexity — O(1)</li></ul><p><strong><em>If you liked this article, don’t forget to leave a clap and follow!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a9e0dec6e41" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>