<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://maxkim77.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://maxkim77.github.io/" rel="alternate" type="text/html" /><updated>2026-01-24T06:31:58+00:00</updated><id>https://maxkim77.github.io/feed.xml</id><title type="html">Max Note</title><subtitle>An amazing website.</subtitle><author><name>Max</name><email>maxkim7723@gmail.com</email></author><entry><title type="html">[CodingTest] Java: Binary Search (Problem P1920)</title><link href="https://maxkim77.github.io/codingtest/CodingTestJavaSearch2/" rel="alternate" type="text/html" title="[CodingTest] Java: Binary Search (Problem P1920)" /><published>2025-01-08T00:00:00+00:00</published><updated>2025-01-08T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingTestJavaSearch2</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingTestJavaSearch2/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="solving-problem-p1920-binary-search">Solving Problem P1920: Binary Search</h1>

<h3 id="problem-description">Problem Description</h3>

<p>You are given an integer <strong>N</strong> and an array <strong>A</strong> of <strong>N</strong> integers. Then you receive an integer <strong>M</strong> and <strong>M</strong> queries, each query being a target integer. For each target, output <strong>1</strong> if it exists in <strong>A</strong>, or <strong>0</strong> if it does not.</p>

<h3 id="constraints">Constraints</h3>

<ul>
  <li>1 ≤ N ≤ 100,000 (Number of elements in the array)</li>
  <li>1 ≤ M ≤ 100,000 (Number of queries)</li>
  <li>Array elements and search targets can be in the range of a 32-bit integer (−2,147,483,648 to 2,147,483,647)</li>
</ul>

<h3 id="input-format">Input Format</h3>

<ol>
  <li>The first line contains an integer <strong>N</strong>, the size of the array.</li>
  <li>The second line contains <strong>N</strong> integers (the elements of <strong>A</strong>).</li>
  <li>The third line contains an integer <strong>M</strong>, the number of queries.</li>
  <li>The next line contains <strong>M</strong> integers (each one is a target to search for in <strong>A</strong>).</li>
</ol>

<h3 id="output-format">Output Format</h3>

<ul>
  <li>For each of the <strong>M</strong> targets, print <strong>1</strong> if the target exists in the array <strong>A</strong>, otherwise print <strong>0</strong>.</li>
</ul>

<hr />

<h3 id="example-input-and-output">Example Input and Output</h3>

<h4 id="example">Example</h4>

<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5
4 1 5 2 3
5
1 3 7 9 5
</code></pre></div></div>

<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
1
0
0
1
</code></pre></div></div>

<p><strong>Explanation:</strong></p>
<ul>
  <li><strong>1</strong> is in the array → output <strong>1</strong></li>
  <li><strong>3</strong> is in the array → output <strong>1</strong></li>
  <li><strong>7</strong> is not in the array → output <strong>0</strong></li>
  <li><strong>9</strong> is not in the array → output <strong>0</strong></li>
  <li><strong>5</strong> is in the array → output <strong>1</strong></li>
</ul>

<hr />

<h3 id="concept-of-binary-search">Concept of Binary Search</h3>

<p>Binary search is an efficient algorithm for finding a target value within a sorted array. It repeatedly divides the search interval in half:</p>
<ul>
  <li>Start with the entire array as the search interval.</li>
  <li>Compare the middle element with the target.</li>
  <li>If the target equals the middle element, the search is successful.</li>
  <li>If the target is smaller, narrow the interval to the left half.</li>
  <li>If the target is larger, narrow the interval to the right half.</li>
</ul>

<h4 id="time-complexity">Time Complexity</h4>

<ul>
  <li>Sorting the array: O(N log N)</li>
  <li>Binary search for each query: O(log N)</li>
  <li>Total for M queries: O(M log N)</li>
  <li>Overall complexity: O(N log N + M log N)</li>
</ul>

<h4 id="space-complexity">Space Complexity</h4>

<ul>
  <li>O(N): Space for the array and auxiliary data.</li>
</ul>

<hr />

<h3 id="approach">Approach</h3>

<ol>
  <li><strong>Sort the array</strong> of size <strong>N</strong> to enable binary search.</li>
  <li>For each target in the <strong>M</strong> queries:
    <ul>
      <li>Use binary search to determine whether the target exists.</li>
      <li>Print <strong>1</strong> if found, otherwise <strong>0</strong>.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="pseudocode">Pseudocode</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>BEGIN
  READ N, the size of the array
  READ array A of size N
  SORT array A

  READ M, the number of queries
  FOR each query target in M:
    SET start = 0, end = N - 1, found = false

    WHILE start &lt;= end:
      SET mid = (start + end) / 2
      IF A[mid] == target:
        found = true
        BREAK
      ELSE IF A[mid] &lt; target:
        start = mid + 1
      ELSE:
        end = mid - 1

    PRINT 1 if found, otherwise 0
END
</code></pre></div></div>

<hr />

<h3 id="java-implementation">Java Implementation</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">search</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">P1920</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">Scanner</span> <span class="n">sc</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Scanner</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">in</span><span class="o">);</span>

        <span class="c1">// 1. Read N and the array A</span>
        <span class="kt">int</span> <span class="no">N</span> <span class="o">=</span> <span class="n">sc</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
        <span class="kt">int</span><span class="o">[]</span> <span class="no">A</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">int</span><span class="o">[</span><span class="no">N</span><span class="o">];</span>
        <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">N</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="no">A</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="n">sc</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
        <span class="o">}</span>

        <span class="c1">// 2. Sort the array for efficient binary search</span>
        <span class="nc">Arrays</span><span class="o">.</span><span class="na">sort</span><span class="o">(</span><span class="no">A</span><span class="o">);</span>

        <span class="c1">// 3. Read M and process each query</span>
        <span class="kt">int</span> <span class="no">M</span> <span class="o">=</span> <span class="n">sc</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
        <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">M</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="kt">int</span> <span class="n">target</span> <span class="o">=</span> <span class="n">sc</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
            <span class="kt">boolean</span> <span class="n">found</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span>
            <span class="kt">int</span> <span class="n">start</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
            <span class="kt">int</span> <span class="n">end</span> <span class="o">=</span> <span class="no">N</span> <span class="o">-</span> <span class="mi">1</span><span class="o">;</span>

            <span class="c1">// 4. Perform binary search</span>
            <span class="k">while</span><span class="o">(</span><span class="n">start</span> <span class="o">&lt;=</span> <span class="n">end</span><span class="o">)</span> <span class="o">{</span>
                <span class="kt">int</span> <span class="n">mid</span> <span class="o">=</span> <span class="o">(</span><span class="n">start</span> <span class="o">+</span> <span class="n">end</span><span class="o">)</span> <span class="o">/</span> <span class="mi">2</span><span class="o">;</span>
                <span class="k">if</span><span class="o">(</span><span class="no">A</span><span class="o">[</span><span class="n">mid</span><span class="o">]</span> <span class="o">==</span> <span class="n">target</span><span class="o">)</span> <span class="o">{</span>
                    <span class="n">found</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
                    <span class="k">break</span><span class="o">;</span>
                <span class="o">}</span>
                <span class="k">if</span><span class="o">(</span><span class="no">A</span><span class="o">[</span><span class="n">mid</span><span class="o">]</span> <span class="o">&lt;</span> <span class="n">target</span><span class="o">)</span> <span class="o">{</span>
                    <span class="n">start</span> <span class="o">=</span> <span class="n">mid</span> <span class="o">+</span> <span class="mi">1</span><span class="o">;</span>
                <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
                    <span class="n">end</span> <span class="o">=</span> <span class="n">mid</span> <span class="o">-</span> <span class="mi">1</span><span class="o">;</span>
                <span class="o">}</span>
            <span class="o">}</span>

            <span class="c1">// 5. Print result for this query</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">found</span> <span class="o">?</span> <span class="mi">1</span> <span class="o">:</span> <span class="mi">0</span><span class="o">);</span>
        <span class="o">}</span>

        <span class="n">sc</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<hr />

<h3 id="explanation-of-the-code">Explanation of the Code</h3>

<ol>
  <li><strong>Reading Input</strong>:
    <ul>
      <li>The size of the array (N) and its elements are read into an integer array <code class="language-plaintext highlighter-rouge">A</code>.</li>
      <li>The size of the query set (M) is read, followed by the (M) target values.</li>
    </ul>
  </li>
  <li><strong>Sorting the Array</strong>:
    <ul>
      <li>Sorting ensures that binary search can be applied. This step takes O(N log N).</li>
    </ul>
  </li>
  <li><strong>Binary Search for Each Query</strong>:
    <ul>
      <li>For each target, the algorithm performs binary search over <code class="language-plaintext highlighter-rouge">A</code>.</li>
      <li>A <code class="language-plaintext highlighter-rouge">start</code> pointer begins at the first element, and an <code class="language-plaintext highlighter-rouge">end</code> pointer begins at the last element.</li>
      <li>The midpoint <code class="language-plaintext highlighter-rouge">mid</code> is calculated, and its value is compared to the target.</li>
      <li>Depending on the comparison, the search interval is halved until the target is found or the interval is empty.</li>
    </ul>
  </li>
  <li><strong>Output Results</strong>:
    <ul>
      <li>If the target is found, <strong>1</strong> is printed.</li>
      <li>Otherwise, <strong>0</strong> is printed.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="example-walkthrough">Example Walkthrough</h3>

<h4 id="input">Input:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5
4 1 5 2 3
5
1 3 7 9 5
</code></pre></div></div>

<h4 id="execution">Execution:</h4>

<ol>
  <li><strong>Sorting the Array</strong>:
    <ul>
      <li>Input array: [4, 1, 5, 2, 3]</li>
      <li>Sorted array: [1, 2, 3, 4, 5]</li>
    </ul>
  </li>
  <li><strong>Binary Search for Each Query</strong>:
    <ul>
      <li>Query 1: Target = 1 → Found → Print 1</li>
      <li>Query 2: Target = 3 → Found → Print 1</li>
      <li>Query 3: Target = 7 → Not Found → Print 0</li>
      <li>Query 4: Target = 9 → Not Found → Print 0</li>
      <li>Query 5: Target = 5 → Found → Print 1</li>
    </ul>
  </li>
</ol>

<h4 id="output">Output:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
1
0
0
1
</code></pre></div></div>

<hr />

<h3 id="links">Links</h3>

<ul>
  <li><strong>Problem Link</strong>: <a href="https://www.acmicpc.net/problem/1920">Baekjoon P1920</a></li>
  <li><strong>Graph Traversal Reference</strong>: <a href="https://en.wikipedia.org/wiki/Graph_traversal">Wikipedia</a></li>
</ul>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><category term="CS" /><category term="Java" /><category term="Programming" /><category term="DataStructure" /><category term="Binary_Search" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CodingTest] Java: Search! Counting Connected Components in a Graph (Problem P11724)</title><link href="https://maxkim77.github.io/codingtest/CodingTestJavaSearch/" rel="alternate" type="text/html" title="[CodingTest] Java: Search! Counting Connected Components in a Graph (Problem P11724)" /><published>2025-01-07T00:00:00+00:00</published><updated>2025-01-07T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingTestJavaSearch</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingTestJavaSearch/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="solving-problem-p11724-search-counting-connected-components-in-an-undirected-graph">Solving Problem P11724: Search! Counting Connected Components in an Undirected Graph</h1>

<h3 id="problem-description">Problem Description</h3>

<p>Given an <strong>undirected graph</strong> with <strong>N vertices</strong> and <strong>M edges</strong>, the task is to calculate the number of <strong>connected components</strong> in the graph. A <strong>connected component</strong> is a subset of vertices such that there is a path between any two vertices within the subset, and the subset is not connected to any other vertices outside of it.</p>

<h3 id="constraints">Constraints</h3>

<ul>
  <li><strong>1 ≤ N ≤ 1,000</strong></li>
  <li><strong>0 ≤ M ≤ N × (N - 1) / 2</strong></li>
  <li>Each edge is given as two integers, representing vertices <strong>u</strong> and <strong>v</strong>.</li>
</ul>

<h3 id="input-format">Input Format</h3>

<ol>
  <li>The first line contains two integers <strong>N</strong> (number of vertices) and <strong>M</strong> (number of edges).</li>
  <li>The next <strong>M lines</strong> contain two integers <strong>u</strong> and <strong>v</strong>, representing an undirected edge between vertices <strong>u</strong> and <strong>v</strong>.</li>
</ol>

<h3 id="output-format">Output Format</h3>

<p>Print a single integer, the number of connected components in the graph.</p>

<hr />

<h3 id="example-input-and-output">Example Input and Output</h3>

<h4 id="example-1">Example 1</h4>

<p><strong>Input</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>6 5
1 2
2 5
5 1
3 4
4 6
</code></pre></div></div>

<p><strong>Output</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>2
</code></pre></div></div>

<h4 id="explanation">Explanation</h4>
<ul>
  <li>There are two connected components
    <ul>
      <li>Component 1: {1, 2, 5}</li>
      <li>Component 2: {3, 4, 6}</li>
    </ul>
  </li>
</ul>

<h4 id="example-2">Example 2</h4>

<p><strong>Input</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>6 8
1 2
2 5
5 1
3 4
4 6
5 4
2 4
2 3
</code></pre></div></div>

<p><strong>Output</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
</code></pre></div></div>

<h4 id="explanation-1">Explanation</h4>
<ul>
  <li>There is one connected component containing all vertices: {1, 2, 3, 4, 5, 6}.</li>
</ul>

<hr />

<h3 id="approach-depth-first-search-dfs">Approach: Depth-First Search (DFS)</h3>

<p>To solve the problem, we use <strong>Depth-First Search (DFS)</strong> to traverse each connected component in the graph. The idea is to start at an unvisited vertex, traverse all reachable vertices, and count the number of times we initiate a new traversal.</p>

<h4 id="key-idea">Key Idea</h4>
<ol>
  <li>Use an adjacency list to represent the graph.</li>
  <li>Maintain a visited array to keep track of visited vertices.</li>
  <li>For each vertex, if it has not been visited, initiate a DFS traversal and increment the connected components count.</li>
</ol>

<h4 id="complexity">Complexity</h4>
<ul>
  <li><strong>Time Complexity:</strong> ( O(N + M) )
    <ul>
      <li>Traversing all vertices and edges in the graph.</li>
    </ul>
  </li>
  <li><strong>Space Complexity:</strong> ( O(N + M) )
    <ul>
      <li>Storing the adjacency list and visited array.</li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="java-implementation">Java Implementation</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">search</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.io.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">P11724</span> <span class="o">{</span>
    <span class="kd">static</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;[]</span> <span class="no">A</span><span class="o">;</span>
    <span class="kd">static</span> <span class="kt">boolean</span> <span class="n">visited</span><span class="o">[];</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">IOException</span> <span class="o">{</span>
        <span class="nc">BufferedReader</span> <span class="n">br</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">InputStreamReader</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">in</span><span class="o">));</span>
        <span class="nc">StringTokenizer</span> <span class="n">st</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">br</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
        <span class="kt">int</span> <span class="n">n</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">st</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
        <span class="kt">int</span> <span class="n">m</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">st</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>

        <span class="c1">// Initialize adjacency list and visited array</span>
        <span class="no">A</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">[</span><span class="n">n</span> <span class="o">+</span> <span class="mi">1</span><span class="o">];</span>
        <span class="n">visited</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">boolean</span><span class="o">[</span><span class="n">n</span> <span class="o">+</span> <span class="mi">1</span><span class="o">];</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="n">n</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="no">A</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;&gt;();</span>
        <span class="o">}</span>

        <span class="c1">// Read edges and populate adjacency list</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">m</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="n">st</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">br</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
            <span class="kt">int</span> <span class="n">s</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">st</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
            <span class="kt">int</span> <span class="n">e</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">st</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
            <span class="no">A</span><span class="o">[</span><span class="n">s</span><span class="o">].</span><span class="na">add</span><span class="o">(</span><span class="n">e</span><span class="o">);</span>
            <span class="no">A</span><span class="o">[</span><span class="n">e</span><span class="o">].</span><span class="na">add</span><span class="o">(</span><span class="n">s</span><span class="o">);</span> <span class="c1">// Undirected graph</span>
        <span class="o">}</span>

        <span class="kt">int</span> <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

        <span class="c1">// Perform DFS for each unvisited vertex</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="n">n</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="k">if</span> <span class="o">(!</span><span class="n">visited</span><span class="o">[</span><span class="n">i</span><span class="o">])</span> <span class="o">{</span>
                <span class="n">count</span><span class="o">++;</span>
                <span class="no">DFS</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
            <span class="o">}</span>
        <span class="o">}</span>

        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">count</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="kd">static</span> <span class="kt">void</span> <span class="nf">DFS</span><span class="o">(</span><span class="kt">int</span> <span class="n">v</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">visited</span><span class="o">[</span><span class="n">v</span><span class="o">])</span> <span class="o">{</span>
            <span class="k">return</span><span class="o">;</span>
        <span class="o">}</span>
        <span class="n">visited</span><span class="o">[</span><span class="n">v</span><span class="o">]</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">:</span> <span class="no">A</span><span class="o">[</span><span class="n">v</span><span class="o">])</span> <span class="o">{</span>
            <span class="k">if</span> <span class="o">(!</span><span class="n">visited</span><span class="o">[</span><span class="n">i</span><span class="o">])</span> <span class="o">{</span>
                <span class="no">DFS</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<hr />

<h3 id="pseudocode">Pseudocode</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>BEGIN
    READ n, m (number of vertices and edges)

    CREATE adjacency list A of size n + 1
    CREATE visited array of size n + 1, initialized to false

    FOR i FROM 1 TO n DO
        A[i] = new empty list
    END FOR

    FOR i FROM 0 TO m DO
        READ edge (s, e)
        ADD e to A[s]
        ADD s to A[e] (undirected graph)
    END FOR

    SET count = 0

    FOR i FROM 1 TO n DO
        IF visited[i] IS false THEN
            INCREMENT count
            CALL DFS(i)
        END IF
    END FOR

    PRINT count
END

FUNCTION DFS(v):
    IF visited[v] IS true THEN
        RETURN
    END IF

    SET visited[v] = true

    FOR each neighbor i in A[v]:
        IF visited[i] IS false THEN
            CALL DFS(i)
        END IF
    END FOR
END FUNCTION
</code></pre></div></div>

<hr />

<h3 id="explanation-of-the-code">Explanation of the Code</h3>

<ol>
  <li><strong>Graph Representation</strong>
    <ul>
      <li>The graph is represented using an <strong>adjacency list</strong>, which is memory-efficient compared to an adjacency matrix for sparse graphs.</li>
    </ul>
  </li>
  <li><strong>DFS Traversal</strong>
    <ul>
      <li>The DFS function recursively visits all vertices in the current connected component.</li>
      <li>The <code class="language-plaintext highlighter-rouge">visited</code> array ensures that each vertex is visited only once.</li>
    </ul>
  </li>
  <li><strong>Counting Connected Components</strong>
    <ul>
      <li>For each unvisited vertex, we initiate a DFS traversal and increment the connected components count.</li>
    </ul>
  </li>
  <li><strong>Output</strong>
    <ul>
      <li>The final count of connected components is printed.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="walkthrough-with-example">Walkthrough with Example</h3>

<h4 id="input">Input:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>6 5
1 2
2 5
5 1
3 4
4 6
</code></pre></div></div>

<h4 id="steps">Steps:</h4>
<ol>
  <li>Build adjacency list
    <ul>
      <li>Vertex 1: [2, 5]</li>
      <li>Vertex 2: [1, 5]</li>
      <li>Vertex 3: [4]</li>
      <li>Vertex 4: [3, 6]</li>
      <li>Vertex 5: [1, 2]</li>
      <li>Vertex 6: [4]</li>
    </ul>
  </li>
  <li>Perform DFS
    <ul>
      <li>Start at vertex 1, traverse {1, 2, 5} (Component 1).</li>
      <li>Move to vertex 3, traverse {3, 4, 6} (Component 2).</li>
    </ul>
  </li>
  <li>Count = 2.</li>
</ol>

<h4 id="output">Output:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>2
</code></pre></div></div>

<hr />

<h3 id="complexity-analysis">Complexity Analysis</h3>

<ul>
  <li><strong>Time Complexity:</strong> ( O(N + M) )
    <ul>
      <li>DFS visits each vertex and edge once.</li>
    </ul>
  </li>
  <li><strong>Space Complexity:</strong> ( O(N + M) )
    <ul>
      <li>For the adjacency list and visited array.</li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="links">Links</h3>

<ul>
  <li><strong>Problem Link</strong>: <a href="https://www.acmicpc.net/problem/11724">Baekjoon P11724</a></li>
  <li><strong>Graph Theory Reference</strong>: <a href="https://en.wikipedia.org/wiki/Graph_theory">Wikipedia</a></li>
</ul>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CodingTest] Java: Depth-First Search (DFS) and Breadth-First Search (BFS)</title><link href="https://maxkim77.github.io/codingtest/CodingTestJavaSearch1/" rel="alternate" type="text/html" title="[CodingTest] Java: Depth-First Search (DFS) and Breadth-First Search (BFS)" /><published>2025-01-07T00:00:00+00:00</published><updated>2025-01-07T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingTestJavaSearch1</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingTestJavaSearch1/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="solving-problem-p1260-dfs-and-bfs-traversal-of-a-graph">Solving Problem P1260: DFS and BFS Traversal of a Graph</h1>

<h3 id="problem-description">Problem Description</h3>

<p>Given an <strong>undirected graph</strong> with <strong>N vertices</strong> and <strong>M edges</strong>, perform:</p>
<ol>
  <li><strong>Depth-First Search (DFS)</strong> starting from a given vertex.</li>
  <li><strong>Breadth-First Search (BFS)</strong> starting from the same vertex.</li>
</ol>

<p>For both traversals, visit vertices in ascending numerical order when multiple vertices are reachable.</p>

<h3 id="constraints">Constraints</h3>

<ul>
  <li><strong>1 ≤ N ≤ 1,000</strong> (Number of vertices)</li>
  <li><strong>1 ≤ M ≤ 10,000</strong> (Number of edges)</li>
</ul>

<h3 id="input-format">Input Format</h3>

<ol>
  <li>The first line contains three integers <strong>N</strong> (number of vertices), <strong>M</strong> (number of edges), and <strong>V</strong> (starting vertex).</li>
  <li>The next <strong>M lines</strong> contain two integers <strong>u</strong> and <strong>v</strong>, representing an undirected edge between vertices <strong>u</strong> and <strong>v</strong>.</li>
</ol>

<h3 id="output-format">Output Format</h3>

<ol>
  <li>Print the order of vertices visited by DFS on the first line.</li>
  <li>Print the order of vertices visited by BFS on the second line.</li>
</ol>

<hr />

<h3 id="example-input-and-output">Example Input and Output</h3>

<h4 id="example-1">Example 1</h4>

<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>4 5 1
1 2
1 3
1 4
2 4
3 4
</code></pre></div></div>

<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1 2 4 3
1 2 3 4
</code></pre></div></div>

<h4 id="example-2">Example 2</h4>

<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5 5 3
5 4
5 2
1 2
3 4
3 1
</code></pre></div></div>

<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>3 1 2 5 4
3 1 4 2 5
</code></pre></div></div>

<h4 id="example-3">Example 3</h4>

<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1000 1 1000
999 1000
</code></pre></div></div>

<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1000 999
1000 999
</code></pre></div></div>

<hr />

<h3 id="approach-graph-traversal-with-dfs-and-bfs">Approach: Graph Traversal with DFS and BFS</h3>

<p>To solve the problem, we use <strong>DFS</strong> and <strong>BFS</strong> traversal algorithms. Both algorithms rely on the adjacency list representation of the graph to efficiently manage edges.</p>

<h4 id="depth-first-search-dfs">Depth-First Search (DFS)</h4>
<ul>
  <li>DFS uses recursion or a stack to explore as deep as possible along each branch before backtracking.</li>
  <li>It is implemented here using recursion.</li>
</ul>

<h4 id="breadth-first-search-bfs">Breadth-First Search (BFS)</h4>
<ul>
  <li>BFS uses a queue to explore all neighbors of a vertex before moving to the next level.</li>
  <li>This ensures that vertices are visited in increasing order of distance from the starting vertex.</li>
</ul>

<h4 id="complexity">Complexity</h4>
<ul>
  <li><strong>Time Complexity:</strong> ( O(N + M) )
    <ul>
      <li>Traverses all vertices and edges.</li>
    </ul>
  </li>
  <li><strong>Space Complexity:</strong> ( O(N + M) )
    <ul>
      <li>Adjacency list and visited array.</li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="java-implementation">Java Implementation</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">search</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">P1260</span> <span class="o">{</span>
    <span class="kd">static</span> <span class="kt">boolean</span> <span class="n">visited</span><span class="o">[];</span>
    <span class="kd">static</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;[]</span> <span class="no">A</span><span class="o">;</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">Scanner</span> <span class="n">scan</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Scanner</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">in</span><span class="o">);</span>
        <span class="kt">int</span> <span class="no">N</span> <span class="o">=</span> <span class="n">scan</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
        <span class="kt">int</span> <span class="no">M</span> <span class="o">=</span> <span class="n">scan</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
        <span class="kt">int</span> <span class="nc">Start</span> <span class="o">=</span> <span class="n">scan</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>

        <span class="no">A</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">[</span><span class="no">N</span> <span class="o">+</span> <span class="mi">1</span><span class="o">];</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="no">N</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="no">A</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;();</span>
        <span class="o">}</span>

        <span class="c1">// Read edges and populate adjacency list</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">M</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="kt">int</span> <span class="no">S</span> <span class="o">=</span> <span class="n">scan</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
            <span class="kt">int</span> <span class="no">E</span> <span class="o">=</span> <span class="n">scan</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
            <span class="no">A</span><span class="o">[</span><span class="no">S</span><span class="o">].</span><span class="na">add</span><span class="o">(</span><span class="no">E</span><span class="o">);</span>
            <span class="no">A</span><span class="o">[</span><span class="no">E</span><span class="o">].</span><span class="na">add</span><span class="o">(</span><span class="no">S</span><span class="o">);</span> <span class="c1">// Undirected graph</span>
        <span class="o">}</span>

        <span class="c1">// Sort adjacency list for consistent traversal order</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="no">N</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="nc">Collections</span><span class="o">.</span><span class="na">sort</span><span class="o">(</span><span class="no">A</span><span class="o">[</span><span class="n">i</span><span class="o">]);</span>
        <span class="o">}</span>

        <span class="c1">// DFS traversal</span>
        <span class="n">visited</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">boolean</span><span class="o">[</span><span class="no">N</span> <span class="o">+</span> <span class="mi">1</span><span class="o">];</span>
        <span class="no">DFS</span><span class="o">(</span><span class="nc">Start</span><span class="o">);</span>
        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">();</span>

        <span class="c1">// BFS traversal</span>
        <span class="n">visited</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">boolean</span><span class="o">[</span><span class="no">N</span> <span class="o">+</span> <span class="mi">1</span><span class="o">];</span>
        <span class="no">BFS</span><span class="o">(</span><span class="nc">Start</span><span class="o">);</span>
        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">();</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">DFS</span><span class="o">(</span><span class="kt">int</span> <span class="nc">Node</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="nc">Node</span> <span class="o">+</span> <span class="s">" "</span><span class="o">);</span>
        <span class="n">visited</span><span class="o">[</span><span class="nc">Node</span><span class="o">]</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">:</span> <span class="no">A</span><span class="o">[</span><span class="nc">Node</span><span class="o">])</span> <span class="o">{</span>
            <span class="k">if</span> <span class="o">(!</span><span class="n">visited</span><span class="o">[</span><span class="n">i</span><span class="o">])</span> <span class="o">{</span>
                <span class="no">DFS</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="kd">private</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">BFS</span><span class="o">(</span><span class="kt">int</span> <span class="nc">Node</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">Queue</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">queue</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LinkedList</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;();</span>
        <span class="n">queue</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="nc">Node</span><span class="o">);</span>
        <span class="n">visited</span><span class="o">[</span><span class="nc">Node</span><span class="o">]</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>

        <span class="k">while</span> <span class="o">(!</span><span class="n">queue</span><span class="o">.</span><span class="na">isEmpty</span><span class="o">())</span> <span class="o">{</span>
            <span class="kt">int</span> <span class="n">now_Node</span> <span class="o">=</span> <span class="n">queue</span><span class="o">.</span><span class="na">poll</span><span class="o">();</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="n">now_Node</span> <span class="o">+</span> <span class="s">" "</span><span class="o">);</span>
            <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">:</span> <span class="no">A</span><span class="o">[</span><span class="n">now_Node</span><span class="o">])</span> <span class="o">{</span>
                <span class="k">if</span> <span class="o">(!</span><span class="n">visited</span><span class="o">[</span><span class="n">i</span><span class="o">])</span> <span class="o">{</span>
                    <span class="n">visited</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
                    <span class="n">queue</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
                <span class="o">}</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<hr />

<h3 id="pseudocode">Pseudocode</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>BEGIN
    READ N, M, V (number of vertices, edges, starting vertex)
    INITIALIZE adjacency list A[N+1] and visited array

    FOR each edge (S, E):
        ADD E to A[S]
        ADD S to A[E] (undirected graph)
    END FOR

    FOR each adjacency list A[i]:
        SORT A[i]
    END FOR

    INITIALIZE visited array to false
    CALL DFS(V)
    PRINT DFS order

    INITIALIZE visited array to false
    CALL BFS(V)
    PRINT BFS order
END

FUNCTION DFS(Node):
    PRINT Node
    SET visited[Node] = true
    FOR each neighbor i in A[Node]:
        IF visited[i] IS false THEN
            CALL DFS(i)
        END IF
    END FOR
END FUNCTION

FUNCTION BFS(Node):
    INITIALIZE queue
    ENQUEUE Node
    SET visited[Node] = true

    WHILE queue IS NOT EMPTY:
        DEQUEUE current_Node
        PRINT current_Node
        FOR each neighbor i in A[current_Node]:
            IF visited[i] IS false THEN
                ENQUEUE i
                SET visited[i] = true
            END IF
        END FOR
    END WHILE
END FUNCTION
</code></pre></div></div>

<hr />

<h3 id="explanation-of-the-code">Explanation of the Code</h3>

<ol>
  <li><strong>Graph Representation:</strong>
    <ul>
      <li>The graph is represented using an <strong>adjacency list</strong> to store all edges efficiently.</li>
    </ul>
  </li>
  <li><strong>DFS Traversal:</strong>
    <ul>
      <li>Recursive DFS is used to visit each vertex and its neighbors in depth-first order.</li>
      <li>The <code class="language-plaintext highlighter-rouge">visited</code> array ensures that each vertex is visited only once.</li>
    </ul>
  </li>
  <li><strong>BFS Traversal:</strong>
    <ul>
      <li>Iterative BFS uses a queue to process vertices level by level.</li>
      <li>The <code class="language-plaintext highlighter-rouge">visited</code> array ensures that each vertex is added to the queue only once.</li>
    </ul>
  </li>
  <li><strong>Sorting:</strong>
    <ul>
      <li>Sorting the adjacency list ensures that vertices are visited in ascending order when multiple options are available.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="walkthrough-with-example">Walkthrough with Example</h3>

<h4 id="input">Input:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>4 5 1
1 2
1 3
1 4
2 4
3 4
</code></pre></div></div>

<h4 id="steps">Steps:</h4>
<ol>
  <li>Build adjacency list:
    <ul>
      <li>Vertex 1: [2, 3, 4]</li>
      <li>Vertex 2: [1, 4]</li>
      <li>Vertex 3: [1, 4]</li>
      <li>Vertex 4: [1, 2, 3]</li>
    </ul>
  </li>
  <li>Perform DFS:
    <ul>
      <li>Start at vertex 1 → Visit: 1 → 2 → 4 → 3.</li>
    </ul>
  </li>
  <li>Perform BFS:
    <ul>
      <li>Start at vertex 1 → Visit: 1 → 2 → 3 → 4.</li>
    </ul>
  </li>
</ol>

<h4 id="output">Output:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1 2 4 3
1 2 3 4
</code></pre></div></div>

<hr />

<h3 id="complexity-analysis">Complexity Analysis</h3>

<ul>
  <li><strong>Time Complexity:</strong> ( O(N + M) )
    <ul>
      <li>Traverses all vertices and edges.</li>
    </ul>
  </li>
  <li><strong>Space Complexity:</strong> ( O(N + M) )
    <ul>
      <li>Adjacency list and visited array.</li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="links">Links</h3>

<ul>
  <li><strong>Problem Link</strong>: <a href="https://www.acmicpc.net/problem/1260">Baekjoon P1260</a></li>
  <li><strong>Graph Traversal Reference</strong>: <a href="https://en.wikipedia.org/wiki/Graph_traversal">Wikipedia</a></li>
</ul>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CodingTest] Java: Bubble Sort Algorithm</title><link href="https://maxkim77.github.io/codingtest/CodingTestJavaSort/" rel="alternate" type="text/html" title="[CodingTest] Java: Bubble Sort Algorithm" /><published>2025-01-06T00:00:00+00:00</published><updated>2025-01-06T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingTestJavaSort</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingTestJavaSort/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="solving-sorting-problems-with-bubble-sort-in-java">Solving Sorting Problems with Bubble Sort in Java</h1>

<h3 id="problem-description">Problem Description</h3>

<p>Given an array of <strong>N integers</strong>, the task is to sort the array in ascending order using the <strong>Bubble Sort Algorithm</strong>.</p>

<p>Bubble sort is a simple comparison-based sorting technique where adjacent elements are compared and swapped to place them in the correct order.</p>

<h3 id="input-format">Input Format</h3>

<ol>
  <li>An integer <strong>N</strong>, the number of elements in the array.</li>
  <li><strong>N integers</strong>, representing the array elements.</li>
</ol>

<h3 id="output-format">Output Format</h3>

<p>The sorted array, where each element is printed on a new line.</p>

<hr />

<h3 id="example-input-and-output">Example Input and Output</h3>

<h4 id="example-1">Example 1</h4>

<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5
4 2 5 1 3
</code></pre></div></div>

<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
2
3
4
5
</code></pre></div></div>

<h4 id="explanation">Explanation</h4>
<ul>
  <li>Initial Array: [4, 2, 5, 1, 3]</li>
  <li>After sorting using Bubble Sort:
    <ul>
      <li>[1, 2, 3, 4, 5]</li>
    </ul>
  </li>
  <li>Each element is printed on a new line in ascending order.</li>
</ul>

<hr />

<h3 id="approach-bubble-sort-algorithm">Approach: Bubble Sort Algorithm</h3>

<p>The <strong>Bubble Sort Algorithm</strong> works by repeatedly comparing adjacent elements in the array and swapping them if they are in the wrong order. This process is repeated until the array is fully sorted.</p>

<h4 id="key-idea">Key Idea</h4>

<ol>
  <li>During each iteration, the largest unsorted element “bubbles up” to its correct position at the end of the array.</li>
  <li>The process continues for all elements until the entire array is sorted.</li>
</ol>

<h4 id="steps">Steps</h4>

<ol>
  <li><strong>Compare Adjacent Elements</strong>:
    <ul>
      <li>If the current element is greater than the next element, swap them.</li>
    </ul>
  </li>
  <li><strong>Repeat</strong> the process for all elements, reducing the effective size of the unsorted part of the array after each iteration.</li>
  <li><strong>Stop</strong> when no swaps are needed in a full iteration, indicating the array is sorted.</li>
</ol>

<h4 id="complexity">Complexity</h4>

<ul>
  <li><strong>Time Complexity:</strong>
    <ul>
      <li>Worst Case: ( O(N^2) ) (when the array is sorted in reverse order)</li>
      <li>Best Case: ( O(N) ) (when the array is already sorted, with optimization)</li>
    </ul>
  </li>
  <li><strong>Space Complexity:</strong> ( O(1) ) (no additional memory required apart from the input array)</li>
</ul>

<hr />

<h3 id="java-implementation">Java Implementation</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">java.util.Scanner</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">BubbleSort</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">Scanner</span> <span class="n">sc</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Scanner</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">in</span><span class="o">);</span>

        <span class="c1">// Input the size of the array</span>
        <span class="kt">int</span> <span class="no">N</span> <span class="o">=</span> <span class="n">sc</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
        <span class="kt">int</span><span class="o">[]</span> <span class="n">arr</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">int</span><span class="o">[</span><span class="no">N</span><span class="o">];</span>

        <span class="c1">// Input array elements</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">N</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="n">arr</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="n">sc</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
        <span class="o">}</span>

        <span class="c1">// Perform Bubble Sort</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">N</span> <span class="o">-</span> <span class="mi">1</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">j</span> <span class="o">&lt;</span> <span class="no">N</span> <span class="o">-</span> <span class="mi">1</span><span class="o">;</span> <span class="n">j</span><span class="o">++)</span> <span class="o">{</span>
                <span class="k">if</span> <span class="o">(</span><span class="n">arr</span><span class="o">[</span><span class="n">j</span><span class="o">]</span> <span class="o">&gt;</span> <span class="n">arr</span><span class="o">[</span><span class="n">j</span> <span class="o">+</span> <span class="mi">1</span><span class="o">])</span> <span class="o">{</span>
                    <span class="c1">// Swap elements</span>
                    <span class="kt">int</span> <span class="n">temp</span> <span class="o">=</span> <span class="n">arr</span><span class="o">[</span><span class="n">j</span><span class="o">];</span>
                    <span class="n">arr</span><span class="o">[</span><span class="n">j</span><span class="o">]</span> <span class="o">=</span> <span class="n">arr</span><span class="o">[</span><span class="n">j</span> <span class="o">+</span> <span class="mi">1</span><span class="o">];</span>
                    <span class="n">arr</span><span class="o">[</span><span class="n">j</span> <span class="o">+</span> <span class="mi">1</span><span class="o">]</span> <span class="o">=</span> <span class="n">temp</span><span class="o">;</span>
                <span class="o">}</span>
            <span class="o">}</span>
        <span class="o">}</span>

        <span class="c1">// Output the sorted array</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">N</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">arr</span><span class="o">[</span><span class="n">i</span><span class="o">]);</span>
        <span class="o">}</span>

        <span class="n">sc</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<hr />

<h3 id="pseudocode">Pseudocode</h3>

<p>Here is the pseudocode for the Bubble Sort Algorithm:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>BEGIN
    CREATE Scanner object to read input
    READ N (number of elements in the array)
    CREATE integer array of size N

    FOR i FROM 0 TO N-1 DO
        READ arr[i] (fill the array with input numbers)
    END FOR

    // Bubble sort algorithm
    FOR i FROM 0 TO N-2 DO
        FOR j FROM 0 TO N-2 DO
            IF arr[j] &gt; arr[j+1] THEN
                SWAP arr[j] AND arr[j+1]
            END IF
        END FOR
    END FOR

    // Print sorted array
    FOR i FROM 0 TO N-1 DO
        PRINT arr[i]
    END FOR

    CLOSE Scanner
END
</code></pre></div></div>

<hr />

<h3 id="explanation-of-the-code">Explanation of the Code</h3>

<ol>
  <li><strong>Input Handling</strong>:
    <ul>
      <li>The program reads the size of the array ( N ) and the array elements from the user.</li>
      <li>The array is filled using a loop.</li>
    </ul>
  </li>
  <li><strong>Sorting (Bubble Sort)</strong>:
    <ul>
      <li>Two nested loops are used to perform the sorting:
        <ul>
          <li>The outer loop controls the number of passes (( N-1 )).</li>
          <li>The inner loop compares adjacent elements and swaps them if they are in the wrong order.</li>
        </ul>
      </li>
      <li>After each outer loop iteration, the largest element is guaranteed to be in its correct position.</li>
    </ul>
  </li>
  <li><strong>Output</strong>:
    <ul>
      <li>The sorted array is printed line by line using a loop.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="walkthrough-with-example">Walkthrough with Example</h3>

<h4 id="input">Input:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5
4 2 5 1 3
</code></pre></div></div>

<h4 id="steps-1">Steps:</h4>
<ol>
  <li>
    <p>Initial Array: [4, 2, 5, 1, 3]</p>
  </li>
  <li><strong>Pass 1</strong>:
    <ul>
      <li>Compare 4 and 2: Swap → [2, 4, 5, 1, 3]</li>
      <li>Compare 4 and 5: No swap</li>
      <li>Compare 5 and 1: Swap → [2, 4, 1, 5, 3]</li>
      <li>Compare 5 and 3: Swap → [2, 4, 1, 3, 5]</li>
    </ul>
  </li>
  <li><strong>Pass 2</strong>:
    <ul>
      <li>Compare 2 and 4: No swap</li>
      <li>Compare 4 and 1: Swap → [2, 1, 4, 3, 5]</li>
      <li>Compare 4 and 3: Swap → [2, 1, 3, 4, 5]</li>
    </ul>
  </li>
  <li><strong>Pass 3</strong>:
    <ul>
      <li>Compare 2 and 1: Swap → [1, 2, 3, 4, 5]</li>
    </ul>
  </li>
  <li>Sorted Array: [1, 2, 3, 4, 5]</li>
</ol>

<h4 id="output">Output:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
2
3
4
5
</code></pre></div></div>

<hr />

<h3 id="advantages-and-disadvantages">Advantages and Disadvantages</h3>

<h4 id="advantages">Advantages:</h4>
<ul>
  <li>Simple and easy to understand.</li>
  <li>Suitable for small datasets.</li>
</ul>

<h4 id="disadvantages">Disadvantages:</h4>
<ul>
  <li>Inefficient for large datasets due to its ( O(N^2) ) time complexity.</li>
  <li>Performs unnecessary iterations even if the array is already sorted.</li>
</ul>

<hr />

<h3 id="optimizations-and-alternatives">Optimizations and Alternatives</h3>

<ol>
  <li><strong>Optimization:</strong>
    <ul>
      <li>Add a flag to check if any swaps were made in an iteration.</li>
      <li>If no swaps are made, terminate the loop early.</li>
    </ul>
  </li>
  <li><strong>Better Algorithms:</strong>
    <ul>
      <li><strong>Quick Sort</strong> or <strong>Merge Sort</strong> can handle large datasets efficiently with ( O(N \log N) ) time complexity.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="links">Links</h3>

<ul>
  <li><strong>Bubble Sort Explanation</strong>: <a href="https://en.wikipedia.org/wiki/Bubble_sort">Wikipedia</a></li>
  <li><strong>Source Code Repository</strong>: <a href="https://github.com/maxkim77/javaalgo">GitHub</a></li>
</ul>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><category term="CS" /><category term="Java" /><category term="Programming" /><category term="BubbleSort" /><category term="Sorting" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CodingTest] Java: Sliding Window Minimum (Problem P11003)</title><link href="https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc3/" rel="alternate" type="text/html" title="[CodingTest] Java: Sliding Window Minimum (Problem P11003)" /><published>2025-01-05T00:00:00+00:00</published><updated>2025-01-05T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc3</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc3/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="solving-problem-p11003-sliding-window-minimum-using-deque">Solving Problem P11003: Sliding Window Minimum Using Deque</h1>

<h3 id="problem-description">Problem Description</h3>

<p>Given <strong>N numbers</strong> ( A_1, A_2, \dots, A_N ) and an integer ( L ), the goal is to calculate the minimum value in each sliding window of size ( L ). Specifically, for each ( i ):</p>

<p>[
D_i = \min(A_{i-L+1}, \dots, A_i)
]</p>

<p>When ( i - L + 1 \leq 0 ), ignore indices ( \leq 0 ) while calculating the minimum.</p>

<h3 id="constraints">Constraints</h3>

<ul>
  <li><strong>1 ( \leq ) L ( \leq ) N ( \leq ) 5,000,000</strong></li>
  <li><strong>(-10^9 \leq A_i \leq 10^9)</strong></li>
</ul>

<h3 id="input-format">Input Format</h3>

<ol>
  <li>The first line contains two integers <strong>N</strong> (number of elements) and <strong>L</strong> (window size).</li>
  <li>The second line contains <strong>N integers</strong> ( A_1, A_2, \dots, A_N ).</li>
</ol>

<h3 id="output-format">Output Format</h3>

<p>Output the sliding window minimum values ( D_i ), separated by spaces.</p>

<hr />

<h3 id="example-input-and-output">Example Input and Output</h3>

<h4 id="example-1">Example 1</h4>

<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>12 3
1 5 2 3 6 2 3 7 3 5 2 6
</code></pre></div></div>

<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1 1 1 2 2 2 2 2 3 3 2 2
</code></pre></div></div>

<h4 id="explanation">Explanation</h4>
<ul>
  <li>For each window of size ( L = 3 ):
    <ul>
      <li>Window [1, 5, 2]: Minimum = 1</li>
      <li>Window [5, 2, 3]: Minimum = 1</li>
      <li>Window [2, 3, 6]: Minimum = 2</li>
      <li>Continue similarly…</li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="approach-sliding-window-with-deque">Approach: Sliding Window with Deque</h3>

<p>The problem can be efficiently solved using a <strong>deque</strong> (double-ended queue), which helps maintain the minimum value of the current sliding window.</p>

<h4 id="key-idea">Key Idea</h4>
<ul>
  <li>Use the deque to store indices of array elements. The deque will always maintain elements in increasing order of value.</li>
  <li>Ensure the deque only contains indices that fall within the current sliding window.</li>
</ul>

<h4 id="steps">Steps</h4>

<ol>
  <li><strong>Initialize</strong> a deque to store elements’ indices. This deque will always maintain indices in increasing order of values.</li>
  <li><strong>Iterate</strong> through the array elements:
    <ul>
      <li>Remove elements from the back of the deque if they are greater than the current element. These elements will never be the minimum in the future.</li>
      <li>Add the current element’s index to the deque.</li>
      <li>Remove the front of the deque if it is outside the current sliding window.</li>
      <li>The element at the front of the deque is the minimum for the current sliding window.</li>
    </ul>
  </li>
  <li>Append the minimum to the result for each step.</li>
</ol>

<h4 id="complexity">Complexity</h4>

<ul>
  <li><strong>Time Complexity:</strong> ( O(N) )
    <ul>
      <li>Each element is added and removed from the deque exactly once.</li>
    </ul>
  </li>
  <li><strong>Space Complexity:</strong> ( O(L) ), where ( L ) is the maximum size of the deque.</li>
</ul>

<hr />

<h3 id="java-implementation">Java Implementation</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">datastruc.R1</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.io.BufferedReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.BufferedWriter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.IOException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.InputStreamReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.OutputStreamWriter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Deque</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.LinkedList</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.StringTokenizer</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">P11003</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">IOException</span> <span class="o">{</span>
        <span class="nc">BufferedReader</span> <span class="n">br</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">InputStreamReader</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">in</span><span class="o">));</span>
        <span class="nc">BufferedWriter</span> <span class="n">bw</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedWriter</span><span class="o">(</span><span class="k">new</span> <span class="nc">OutputStreamWriter</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">));</span>
        <span class="nc">StringTokenizer</span> <span class="n">st</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">br</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
        
        <span class="kt">int</span> <span class="no">N</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">st</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
        <span class="kt">int</span> <span class="no">L</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">st</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
        <span class="n">st</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">br</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>

        <span class="nc">Deque</span><span class="o">&lt;</span><span class="nc">Node</span><span class="o">&gt;</span> <span class="n">mydeque</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LinkedList</span><span class="o">&lt;&gt;();</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">N</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="kt">int</span> <span class="n">now</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">st</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>

            <span class="c1">// Remove elements from back that are greater than the current value</span>
            <span class="k">while</span> <span class="o">(!</span><span class="n">mydeque</span><span class="o">.</span><span class="na">isEmpty</span><span class="o">()</span> <span class="o">&amp;&amp;</span> <span class="n">mydeque</span><span class="o">.</span><span class="na">getLast</span><span class="o">().</span><span class="na">value</span> <span class="o">&gt;</span> <span class="n">now</span><span class="o">)</span> <span class="o">{</span>
                <span class="n">mydeque</span><span class="o">.</span><span class="na">removeLast</span><span class="o">();</span>
            <span class="o">}</span>

            <span class="c1">// Add the current element</span>
            <span class="n">mydeque</span><span class="o">.</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="nc">Node</span><span class="o">(</span><span class="n">now</span><span class="o">,</span> <span class="n">i</span><span class="o">));</span>

            <span class="c1">// Remove elements from front that are out of window</span>
            <span class="k">if</span> <span class="o">(</span><span class="n">mydeque</span><span class="o">.</span><span class="na">getFirst</span><span class="o">().</span><span class="na">index</span> <span class="o">&lt;=</span> <span class="n">i</span> <span class="o">-</span> <span class="no">L</span><span class="o">)</span> <span class="o">{</span>
                <span class="n">mydeque</span><span class="o">.</span><span class="na">removeFirst</span><span class="o">();</span>
            <span class="o">}</span>

            <span class="c1">// Write the minimum value for the current window</span>
            <span class="n">bw</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="n">mydeque</span><span class="o">.</span><span class="na">getFirst</span><span class="o">().</span><span class="na">value</span> <span class="o">+</span> <span class="s">" "</span><span class="o">);</span>
        <span class="o">}</span>

        <span class="n">bw</span><span class="o">.</span><span class="na">flush</span><span class="o">();</span>
        <span class="n">bw</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
    <span class="o">}</span>

    <span class="kd">static</span> <span class="kd">class</span> <span class="nc">Node</span> <span class="o">{</span>
        <span class="kd">public</span> <span class="kt">int</span> <span class="n">value</span><span class="o">;</span>
        <span class="kd">public</span> <span class="kt">int</span> <span class="n">index</span><span class="o">;</span>

        <span class="nc">Node</span><span class="o">(</span><span class="kt">int</span> <span class="n">value</span><span class="o">,</span> <span class="kt">int</span> <span class="n">index</span><span class="o">)</span> <span class="o">{</span>
            <span class="k">this</span><span class="o">.</span><span class="na">value</span> <span class="o">=</span> <span class="n">value</span><span class="o">;</span>
            <span class="k">this</span><span class="o">.</span><span class="na">index</span> <span class="o">=</span> <span class="n">index</span><span class="o">;</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<hr />

<h3 id="pseudocode">Pseudocode</h3>

<p>Here is the pseudocode for the sliding window minimum algorithm:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>BEGIN
  READ N, L
  DECLARE deque as empty

  FOR i FROM 0 TO N - 1 DO
    READ current_element

    // Remove elements from the back of deque if they are greater than the current element
    WHILE deque IS NOT EMPTY AND deque.back.value &gt; current_element DO
      deque.pop_back()
    END WHILE

    // Add current element's index to the deque
    deque.push_back(current_element, index)

    // Remove elements from the front if they are outside the current sliding window
    IF deque.front.index &lt;= i - L THEN
      deque.pop_front()
    END IF

    // Append the minimum (deque.front.value) to the result
    WRITE deque.front.value + " "
  END FOR
END
</code></pre></div></div>

<hr />

<h3 id="explanation-of-the-code">Explanation of the Code</h3>

<ol>
  <li><strong>Input Handling</strong>:
    <ul>
      <li>The program reads the number of elements ( N ) and the sliding window size ( L ).</li>
      <li>It also reads the ( N ) integers into a deque for processing.</li>
    </ul>
  </li>
  <li><strong>Deque Operations</strong>:
    <ul>
      <li>Remove elements from the back of the deque if their value is greater than the current element. These elements will never be the minimum in future windows.</li>
      <li>Remove elements from the front of the deque if they fall outside the sliding window range ([i-L+1, i]).</li>
      <li>The element at the front of the deque is guaranteed to be the minimum for the current window.</li>
    </ul>
  </li>
  <li><strong>Output the Result</strong>:
    <ul>
      <li>For each window, the value at the front of the deque is written as the minimum value.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="complexity-analysis">Complexity Analysis</h3>

<ul>
  <li><strong>Time Complexity:</strong> ( O(N) )
    <ul>
      <li>Each element is added and removed from the deque exactly once, resulting in linear time.</li>
    </ul>
  </li>
  <li><strong>Space Complexity:</strong> ( O(L) )
    <ul>
      <li>The deque contains at most ( L ) elements at any time, where ( L ) is the window size.</li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="links">Links</h3>

<ul>
  <li><strong>Problem Link</strong>: <a href="https://www.acmicpc.net/problem/11003">Baekjoon P11003</a></li>
  <li><strong>Source Code</strong>: <a href="https://github.com/maxkim77/javaalgo">GitHub Repository</a></li>
</ul>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><category term="CS" /><category term="Java" /><category term="Programming" /><category term="DataStructure" /><category term="Sliding_Window" /><category term="Deque" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CodingTest] Java: Two-Pointer Technique for Good Numbers (Problem P1253)</title><link href="https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc2/" rel="alternate" type="text/html" title="[CodingTest] Java: Two-Pointer Technique for Good Numbers (Problem P1253)" /><published>2025-01-04T00:00:00+00:00</published><updated>2025-01-04T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc2</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc2/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="solving-problem-p1253-counting-good-numbers-with-two-pointer-technique">Solving Problem P1253: Counting Good Numbers with Two-Pointer Technique</h1>

<h3 id="problem-description">Problem Description</h3>

<p>Given a sequence of <strong>N integers</strong>, the task is to <strong>count how many of these numbers can be expressed as the sum of two distinct numbers</strong> from the array. A number cannot be used to form itself, but duplicate values are considered distinct if they are at different positions.</p>

<h3 id="constraints">Constraints</h3>

<ul>
  <li><strong>1 ≤ N ≤ 2000</strong></li>
  <li><strong>A[i] ≤ 1,000,000,000</strong></li>
</ul>

<h3 id="input-format">Input Format</h3>

<ol>
  <li>The first line contains an integer <strong>N</strong>, the number of elements in the array.</li>
  <li>The second line contains <strong>N numbers</strong> separated by spaces.</li>
</ol>

<h3 id="output-format">Output Format</h3>

<p>Output a single integer, the count of “good numbers” in the array.</p>

<hr />

<h3 id="example-input-and-output">Example Input and Output</h3>

<h4 id="example-1">Example 1</h4>

<p><strong>Input</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5
1 2 3 4 5
</code></pre></div></div>

<p><strong>Output</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>3
</code></pre></div></div>

<h4 id="explanation">Explanation</h4>
<ul>
  <li><code class="language-plaintext highlighter-rouge">3 = 1 + 2</code></li>
  <li><code class="language-plaintext highlighter-rouge">4 = 1 + 3</code></li>
  <li><code class="language-plaintext highlighter-rouge">5 = 2 + 3</code></li>
  <li>Thus, there are <strong>3</strong> “good numbers”.</li>
</ul>

<h4 id="example-2">Example 2</h4>

<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>4
0 0 0 0
</code></pre></div></div>

<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>4
</code></pre></div></div>

<h4 id="explanation-1">Explanation</h4>
<ul>
  <li>Each <code class="language-plaintext highlighter-rouge">0</code> can be expressed as the sum of two other <code class="language-plaintext highlighter-rouge">0</code>s from different positions.</li>
  <li>Thus, all <strong>4</strong> numbers are “good numbers”.</li>
</ul>

<hr />

<h3 id="approach-two-pointer-technique">Approach: Two-Pointer Technique</h3>

<p>To efficiently count the “good numbers” in the array, we can utilize the <strong>two-pointer technique</strong>. Here’s a step-by-step approach:</p>

<h4 id="steps">Steps:</h4>

<ol>
  <li><strong>Sort the Array</strong>:
    <ul>
      <li>First, sort the array in ascending order. Sorting helps in efficiently finding pairs that sum up to a target value using two pointers.</li>
    </ul>
  </li>
  <li><strong>Iterate Through Each Number</strong>:
    <ul>
      <li>For each number in the array, consider it as the target sum and use two pointers to find if there exists a pair that sums up to this target.</li>
    </ul>
  </li>
  <li><strong>Initialize Two Pointers</strong>:
    <ul>
      <li>Initialize one pointer at the start (<code class="language-plaintext highlighter-rouge">i = 0</code>) and another at the end (<code class="language-plaintext highlighter-rouge">j = N-1</code>) of the array.</li>
      <li>If either pointer points to the current target index, move the pointer accordingly to avoid using the number itself.</li>
    </ul>
  </li>
  <li><strong>Check Sum</strong>:
    <ul>
      <li>Calculate the sum of the numbers at the two pointers.</li>
      <li>If the sum equals the target, increment the count of “good numbers” and move to the next target.</li>
      <li>If the sum is less than the target, move the left pointer to the right to increase the sum.</li>
      <li>If the sum is greater than the target, move the right pointer to the left to decrease the sum.</li>
    </ul>
  </li>
  <li><strong>Avoid Counting Duplicates</strong>:
    <ul>
      <li>Ensure that the same pair isn’t counted multiple times by breaking out of the loop once a valid pair is found.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="java-implementation">Java Implementation</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">datastruc.R1</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.io.BufferedReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.IOException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.InputStreamReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Arrays</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.StringTokenizer</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">P1253</span> <span class="o">{</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">IOException</span> <span class="o">{</span>
        <span class="nc">BufferedReader</span> <span class="n">bf</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">InputStreamReader</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">in</span><span class="o">));</span>
        <span class="kt">int</span> <span class="no">N</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">bf</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
        <span class="kt">int</span> <span class="nc">Result</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
        <span class="kt">long</span> <span class="no">A</span><span class="o">[]</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">long</span><span class="o">[</span><span class="no">N</span><span class="o">];</span>
        <span class="nc">StringTokenizer</span> <span class="n">st</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">bf</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
        <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">N</span><span class="o">;</span> <span class="n">i</span><span class="o">++){</span>
            <span class="no">A</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="nc">Long</span><span class="o">.</span><span class="na">parseLong</span><span class="o">(</span><span class="n">st</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
        <span class="o">}</span>
        <span class="nc">Arrays</span><span class="o">.</span><span class="na">sort</span><span class="o">(</span><span class="no">A</span><span class="o">);</span> <span class="c1">// Sort the array in ascending order</span>

        <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">k</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">k</span> <span class="o">&lt;</span> <span class="no">N</span><span class="o">;</span> <span class="n">k</span><span class="o">++){</span> <span class="c1">// Iterate through each number as the target</span>
            <span class="kt">long</span> <span class="n">find</span> <span class="o">=</span> <span class="no">A</span><span class="o">[</span><span class="n">k</span><span class="o">];</span>
            <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
            <span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="no">N</span> <span class="o">-</span> <span class="mi">1</span><span class="o">;</span> <span class="c1">// Initialize two pointers</span>
            <span class="k">while</span><span class="o">(</span><span class="n">i</span> <span class="o">&lt;</span> <span class="n">j</span><span class="o">){</span>
                <span class="k">if</span><span class="o">(</span><span class="no">A</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">+</span> <span class="no">A</span><span class="o">[</span><span class="n">j</span><span class="o">]</span> <span class="o">==</span> <span class="n">find</span><span class="o">){</span>
                    <span class="k">if</span><span class="o">(</span><span class="n">i</span> <span class="o">!=</span> <span class="n">k</span> <span class="o">&amp;&amp;</span> <span class="n">j</span> <span class="o">!=</span> <span class="n">k</span><span class="o">){</span>
                        <span class="nc">Result</span><span class="o">++;</span>
                        <span class="k">break</span><span class="o">;</span>
                    <span class="o">}</span> <span class="k">else</span> <span class="k">if</span><span class="o">(</span><span class="n">i</span> <span class="o">==</span> <span class="n">k</span><span class="o">){</span>
                        <span class="n">i</span><span class="o">++;</span>
                    <span class="o">}</span> <span class="k">else</span> <span class="k">if</span><span class="o">(</span><span class="n">j</span> <span class="o">==</span> <span class="n">k</span><span class="o">){</span>
                        <span class="n">j</span><span class="o">--;</span>
                    <span class="o">}</span>     
                <span class="o">}</span>
                <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="no">A</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">+</span> <span class="no">A</span><span class="o">[</span><span class="n">j</span><span class="o">]</span> <span class="o">&lt;</span> <span class="n">find</span><span class="o">){</span>
                    <span class="n">i</span><span class="o">++;</span>
                <span class="o">}</span> <span class="k">else</span><span class="o">{</span>
                    <span class="n">j</span><span class="o">--;</span>
                <span class="o">}</span>
            <span class="o">}</span>
        <span class="o">}</span>
        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="nc">Result</span><span class="o">);</span>
        <span class="n">bf</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<hr />

<h3 id="explanation-of-the-code">Explanation of the Code</h3>

<ol>
  <li><strong>Input Handling</strong>:
    <ul>
      <li>The program reads the number of elements <code class="language-plaintext highlighter-rouge">N</code> and the array <code class="language-plaintext highlighter-rouge">A</code> from the standard input using <code class="language-plaintext highlighter-rouge">BufferedReader</code> and <code class="language-plaintext highlighter-rouge">StringTokenizer</code> for efficient input processing.</li>
    </ul>
  </li>
  <li><strong>Sorting</strong>:
    <ul>
      <li>The array <code class="language-plaintext highlighter-rouge">A</code> is sorted in ascending order using <code class="language-plaintext highlighter-rouge">Arrays.sort(A)</code>. Sorting is crucial for the two-pointer technique to work efficiently.</li>
    </ul>
  </li>
  <li><strong>Counting Good Numbers</strong>:
    <ul>
      <li>The outer loop iterates through each element in the sorted array, treating each as the target sum (<code class="language-plaintext highlighter-rouge">find</code>).</li>
      <li>For each target, two pointers <code class="language-plaintext highlighter-rouge">i</code> and <code class="language-plaintext highlighter-rouge">j</code> are initialized at the start and end of the array, respectively.</li>
      <li>The inner loop moves the pointers based on the sum of <code class="language-plaintext highlighter-rouge">A[i] + A[j]</code> compared to the target:
        <ul>
          <li><strong>If the sum equals the target</strong> and neither pointer is pointing to the target index (<code class="language-plaintext highlighter-rouge">k</code>), it’s a “good number”, and <code class="language-plaintext highlighter-rouge">Result</code> is incremented.</li>
          <li><strong>If either pointer points to the target index</strong>, the pointer is moved to avoid using the number itself.</li>
          <li><strong>If the sum is less than the target</strong>, the left pointer <code class="language-plaintext highlighter-rouge">i</code> is moved to the right to increase the sum.</li>
          <li><strong>If the sum is greater than the target</strong>, the right pointer <code class="language-plaintext highlighter-rouge">j</code> is moved to the left to decrease the sum.</li>
        </ul>
      </li>
      <li>The loop breaks once a valid pair is found for the current target.</li>
    </ul>
  </li>
  <li><strong>Output</strong>:
    <ul>
      <li>After processing all elements, the total count of “good numbers” is printed.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="complexity-analysis">Complexity Analysis</h3>

<ul>
  <li><strong>Sorting</strong>: (O(N \log N))</li>
  <li><strong>Counting Good Numbers</strong>: (O(N^2))
    <ul>
      <li>Outer loop runs (N) times.</li>
      <li>Inner loop (two-pointer search) runs (O(N)) for each target.</li>
    </ul>
  </li>
  <li><strong>Total Complexity</strong>: (O(N^2))</li>
</ul>

<hr />

<h3 id="links">Links</h3>

<ul>
  <li><strong>Problem Link</strong>: <a href="https://www.acmicpc.net/problem/1253">Baekjoon P1253</a></li>
  <li><strong>Source Code</strong>: <a href="https://github.com/maxkim77/javaalgo">GitHub Repository</a></li>
</ul>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><category term="CS" /><category term="Java" /><category term="Programming" /><category term="DataStructure" /><category term="Two_Pointer" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CodingTest] Java: Range Sum Query (Prefix Sum)</title><link href="https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc1/" rel="alternate" type="text/html" title="[CodingTest] Java: Range Sum Query (Prefix Sum)" /><published>2025-01-03T00:00:00+00:00</published><updated>2025-01-03T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc1</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingTestJavaDatastruc1/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="solving-problem-11659-prefix-sum-for-range-queries">Solving Problem 11659: Prefix Sum for Range Queries</h1>

<h3 id="problem-description">Problem Description</h3>
<p>Given <strong>N numbers</strong>, the task is to efficiently calculate the sum of numbers from the (i^th) to the (j^th) index for multiple queries.</p>

<h3 id="constraints">Constraints</h3>
<ul>
  <li><strong>1 ≤ N ≤ 100,000</strong></li>
  <li><strong>1 ≤ M ≤ 100,000</strong></li>
  <li><strong>1 ≤ i ≤ j ≤ N</strong></li>
  <li>The numbers are natural numbers (≤ 1000).</li>
</ul>

<h3 id="input-format">Input Format</h3>
<ol>
  <li>The first line contains two integers, <strong>N</strong> (number of numbers) and <strong>M</strong> (number of queries).</li>
  <li>The second line contains <strong>N numbers</strong> separated by spaces.</li>
  <li>Each of the next <strong>M lines</strong> contains two integers <strong>i</strong> and <strong>j</strong>, representing the range for which the sum needs to be calculated.</li>
</ol>

<h3 id="output-format">Output Format</h3>
<p>For each query, output the sum of numbers from the (i^th) to the (j^th) index.</p>

<hr />

<h3 id="example-input-and-output">Example Input and Output</h3>
<h4 id="example-1">Example 1</h4>
<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5 3
5 4 3 2 1
1 3
2 4
5 5
</code></pre></div></div>
<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>12
9
1
</code></pre></div></div>

<h4 id="explanation">Explanation</h4>
<ol>
  <li>Query 1: Sum of elements from index 1 to 3 = 5 + 4 + 3 = 12.</li>
  <li>Query 2: Sum of elements from index 2 to 4 = 4 + 3 + 2 = 9.</li>
  <li>Query 3: Sum of elements from index 5 to 5 = 1.</li>
</ol>

<hr />

<h3 id="approach-prefix-sum-technique">Approach: Prefix Sum Technique</h3>
<p>To efficiently calculate the sum of any range (i) to (j), we use the <strong>prefix sum array</strong> technique.</p>

<h4 id="prefix-sum-formula">Prefix Sum Formula:</h4>
<p>Let (S[k]) be the sum of the first (k) elements of the array.</p>

<ul>
  <li>(S[k] = S[k-1] + A[k])</li>
</ul>

<p>To calculate the sum of elements from index (i) to (j):</p>
<ul>
  <li>(	ext{Range Sum} = S[j] - S[i-1])</li>
</ul>

<h4 id="steps">Steps:</h4>
<ol>
  <li>Precompute the prefix sum array (S) such that (S[k]) contains the sum of the first (k) elements.</li>
  <li>For each query, use the formula (S[j] - S[i-1]) to calculate the sum in constant time (O(1)).</li>
</ol>

<h4 id="complexity">Complexity:</h4>
<ul>
  <li><strong>Prefix Sum Construction</strong>: (O(N))</li>
  <li><strong>Query Handling</strong>: (O(1)) per query</li>
  <li><strong>Total Complexity</strong>: (O(N + M))</li>
</ul>

<hr />

<h3 id="java-implementation">Java Implementation</h3>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">datastruc.R1</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">P11659</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">IOException</span> <span class="o">{</span>
        <span class="nc">BufferedReader</span> <span class="n">bR</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">InputStreamReader</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">in</span><span class="o">));</span>
        <span class="nc">StringTokenizer</span> <span class="n">sT</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">bR</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
        <span class="kt">int</span> <span class="n">arrNum</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">sT</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
        <span class="kt">int</span> <span class="n">queryNum</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">sT</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
        <span class="kt">long</span> <span class="no">S</span><span class="o">[]</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">long</span><span class="o">[</span><span class="n">arrNum</span> <span class="o">+</span> <span class="mi">1</span><span class="o">];</span>

        <span class="c1">// Construct prefix sum array</span>
        <span class="n">sT</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">bR</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="n">arrNum</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="no">S</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="no">S</span><span class="o">[</span><span class="n">i</span> <span class="o">-</span> <span class="mi">1</span><span class="o">]</span> <span class="o">+</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">sT</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
        <span class="o">}</span>

        <span class="c1">// Handle queries</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">l</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">l</span> <span class="o">&lt;</span> <span class="n">queryNum</span><span class="o">;</span> <span class="n">l</span><span class="o">++)</span> <span class="o">{</span>
            <span class="n">sT</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">bR</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
            <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">sT</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
            <span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">sT</span><span class="o">.</span><span class="na">nextToken</span><span class="o">());</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="no">S</span><span class="o">[</span><span class="n">j</span><span class="o">]</span> <span class="o">-</span> <span class="no">S</span><span class="o">[</span><span class="n">i</span> <span class="o">-</span> <span class="mi">1</span><span class="o">]);</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<hr />

<h3 id="explanation-of-the-code">Explanation of the Code</h3>
<ol>
  <li><strong>Input Handling</strong>:
    <ul>
      <li>Read (N) (number of elements) and (M) (number of queries).</li>
      <li>Read the (N) numbers into a prefix sum array.</li>
    </ul>
  </li>
  <li><strong>Prefix Sum Array Construction</strong>:
    <ul>
      <li>(S[i] = S[i-1] + A[i]), where (A[i]) is the (i^{th}) element of the input.</li>
    </ul>
  </li>
  <li><strong>Query Processing</strong>:
    <ul>
      <li>For each query (i, j), calculate (S[j] - S[i-1]) to get the sum of elements from index (i) to (j).</li>
    </ul>
  </li>
  <li><strong>Output</strong>:
    <ul>
      <li>Print the result for each query.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="advantages-of-prefix-sum">Advantages of Prefix Sum</h3>
<ol>
  <li><strong>Efficient Query Handling</strong>: Each query is handled in (O(1)) time, making it suitable for large inputs.</li>
  <li><strong>Precomputation</strong>: Although we spend (O(N)) to construct the prefix sum array, this is a one-time cost that significantly speeds up query handling.</li>
</ol>

<hr />

<h3 id="links">Links</h3>
<ul>
  <li><strong>Problem Link</strong>: <a href="https://www.acmicpc.net/problem/11659">Baekjoon 11659</a></li>
  <li><strong>Source Code</strong>: <a href="https://github.com/maxkim77/javaalgo">GitHub Repository</a></li>
</ul>

<hr />

<h3 id="summary">Summary</h3>
<p>This solution efficiently calculates the sum of any range (i) to (j) using the prefix sum technique. With a time complexity of (O(N + M)), it is well-suited for large inputs and multiple queries.</p>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><category term="CS" /><category term="Java" /><category term="Programming" /><category term="DataStructure" /><category term="Range_Sum" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CodingTest] Java : Sum of Numbers</title><link href="https://maxkim77.github.io/codingtest/CodingtestJavaDatastruc/" rel="alternate" type="text/html" title="[CodingTest] Java : Sum of Numbers" /><published>2025-01-02T00:00:00+00:00</published><updated>2025-01-02T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingtestJavaDatastruc</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingtestJavaDatastruc/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="solving-problem-11720-sum-of-numbers">Solving Problem 11720: Sum of Numbers</h1>

<h3 id="problem-description">Problem Description</h3>
<p>You are given <strong>N numbers</strong> written consecutively without spaces. Write a program to calculate and print the sum of these numbers.</p>

<h3 id="constraints">Constraints</h3>
<ul>
  <li><strong>1 &lt;= N &lt;= 100</strong></li>
  <li>The input numbers are provided without spaces.</li>
</ul>

<h3 id="input-format">Input Format</h3>
<ol>
  <li>The first line contains an integer <strong>N</strong>, the number of digits.</li>
  <li>The second line contains <strong>N consecutive digits</strong> without spaces.</li>
</ol>

<h3 id="output-format">Output Format</h3>
<ul>
  <li>Print the sum of the given digits.</li>
</ul>

<h3 id="examples">Examples</h3>
<h4 id="example-1">Example 1</h4>
<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
1
</code></pre></div></div>
<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
</code></pre></div></div>

<h4 id="example-2">Example 2</h4>
<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5
54321
</code></pre></div></div>
<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>15
</code></pre></div></div>

<h4 id="example-3">Example 3</h4>
<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>25
7000000000000000000000000
</code></pre></div></div>
<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>7
</code></pre></div></div>

<h4 id="example-4">Example 4</h4>
<p><strong>Input:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>11
10987654321
</code></pre></div></div>
<p><strong>Output:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>46
</code></pre></div></div>

<hr />

<h3 id="approach">Approach</h3>
<p>This problem is solved by iterating through each digit of the input string, converting it to an integer, and adding it to a running sum. The approach is straightforward and efficient given the constraint.</p>

<h4 id="steps-to-solve">Steps to Solve:</h4>
<ol>
  <li>Read the input values.</li>
  <li>Convert the string of numbers into a character array.</li>
  <li>Loop through each character, convert it to its numeric value, and add it to the sum.</li>
  <li>Print the total sum.</li>
</ol>

<hr />

<h3 id="java-implementation">Java Implementation</h3>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">datastruc.R1</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">P11720</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">){</span>
        <span class="nc">Scanner</span> <span class="n">sc</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Scanner</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">in</span><span class="o">);</span>
        <span class="kt">int</span> <span class="no">N</span> <span class="o">=</span> <span class="n">sc</span><span class="o">.</span><span class="na">nextInt</span><span class="o">();</span>
        <span class="nc">String</span> <span class="n">sNum</span> <span class="o">=</span> <span class="n">sc</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>

        <span class="c1">// Convert string to char array</span>
        <span class="kt">char</span> <span class="n">cNum</span><span class="o">[]</span> <span class="o">=</span> <span class="n">sNum</span><span class="o">.</span><span class="na">toCharArray</span><span class="o">();</span>
        <span class="kt">int</span> <span class="n">sum</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

        <span class="c1">// Sum each digit</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="no">N</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
            <span class="n">sum</span> <span class="o">+=</span> <span class="n">cNum</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">-</span> <span class="sc">'0'</span><span class="o">;</span> <span class="c1">// Convert char to int by subtracting '0'</span>
        <span class="o">}</span>

        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">sum</span><span class="o">);</span>
        <span class="n">sc</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<hr />

<h3 id="explanation-of-the-code">Explanation of the Code</h3>
<ol>
  <li><strong>Input Handling</strong>:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">Scanner</code> is used to read input.</li>
      <li><code class="language-plaintext highlighter-rouge">nextInt()</code> reads the number of digits ( N ).</li>
      <li><code class="language-plaintext highlighter-rouge">next()</code> reads the string of ( N ) digits.</li>
    </ul>
  </li>
  <li><strong>Character Array Conversion</strong>:
    <ul>
      <li>The <code class="language-plaintext highlighter-rouge">toCharArray()</code> method converts the string into an array of characters, where each character represents a single digit.</li>
    </ul>
  </li>
  <li><strong>Summation Loop</strong>:
    <ul>
      <li>Iterate through each character in the array.</li>
      <li>Convert the character to its integer value by subtracting <code class="language-plaintext highlighter-rouge">'0'</code> (ASCII adjustment).</li>
      <li>Add the integer value to the running total.</li>
    </ul>
  </li>
  <li><strong>Output</strong>:
    <ul>
      <li>Print the total sum.</li>
    </ul>
  </li>
</ol>

<hr />

<h3 id="links">Links</h3>
<ul>
  <li>Problem Link: <a href="https://www.acmicpc.net/problem/11720">Baekjoon 11720</a></li>
  <li>Source Code: <a href="https://github.com/maxkim77/javaalgo">GitHub Repository</a></li>
</ul>

<hr />

<h3 id="summary">Summary</h3>
<p>This solution effectively handles the constraints and uses basic string and array manipulation techniques in Java to solve the problem. The time complexity is ( O(N) ), making it efficient given the problem’s limits.</p>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><category term="CS" /><category term="Java" /><category term="Programming" /><category term="DataStructure" /><category term="Sum_Numbers" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CodingTest] Printing a String in Java</title><link href="https://maxkim77.github.io/codingtest/CodingtestJavaPrint/" rel="alternate" type="text/html" title="[CodingTest] Printing a String in Java" /><published>2024-08-28T00:00:00+00:00</published><updated>2024-08-28T00:00:00+00:00</updated><id>https://maxkim77.github.io/codingtest/CodingtestJavaPrint</id><content type="html" xml:base="https://maxkim77.github.io/codingtest/CodingtestJavaPrint/"><![CDATA[<p><img src="/assets/images/2024-08-28-PrintingaStringinJava/2.png" alt="Codingtest" /></p>

<h1 id="printing-a-string-in-java">Printing a String in Java</h1>

<h3 id="problem-description">Problem Description</h3>

<p>In this post, we’ll explore how to take a string as input and print it in Java. This is a fundamental exercise in understanding basic input/output operations in Java programming.</p>

<p><strong>Problem Statement</strong></p>

<p>Given a string <code class="language-plaintext highlighter-rouge">str</code>, write a program that reads the string and prints it.</p>

<p><strong>Constraints</strong></p>

<ul>
  <li>The length of <code class="language-plaintext highlighter-rouge">str</code> is between 1 and 1,000,000 characters.</li>
  <li>The string <code class="language-plaintext highlighter-rouge">str</code> contains no spaces and is provided in a single line.</li>
</ul>

<h3 id="example-input-and-output">Example Input and Output</h3>

<p><strong>Example Input</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input #1:

HelloWorld!
</code></pre></div></div>

<p><strong>Example Output</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Output #1:

HelloWorld!
</code></pre></div></div>

<h3 id="java-code-implementation">Java Code Implementation</h3>

<details>
    <summary>Details</summary>

<pre><code>

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // Step 1: Create a Scanner object to read input
        String a = sc.next();               // Step 2: Read a single word (without spaces) from the input
        System.out.println(a);              // Step 3: Print the input string
    }
}

</code></pre>

</details>

<h3 id="code-explanation">Code Explanation</h3>

<details>
    <summary>Details</summary>
1. Scanner sc = new Scanner(System.in);
<br />
Here, we create an instance of the Scanner class, named sc, which reads from the standard input (System.in). This allows us to take input from the user.
<br />
<br />
2. String a = sc.next();
<br />
This line reads the next token of input as a string. The next() method of Scanner reads input until a space is encountered, making it ideal for reading a single word.
<br />
<br />
3. System.out.println(a);
<br />
Finally, this line prints the string a to the console. The println method is used to print the output followed by a newline.
<br />
<br />
</details>

<h3 id="concept-summary">Concept Summary</h3>

<ul>
  <li>Scanner Class</li>
</ul>

<p>The Scanner class in Java is a utility that allows for simple input reading from different input streams, like the keyboard. It’s part of the java.util package, which must be imported to use the class.</p>

<ul>
  <li>Main Method</li>
</ul>

<p>The main method serves as the entry point for any Java program. When the program is run, execution begins here.</p>

<ul>
  <li>Reading Input</li>
</ul>

<p>The next() method of the Scanner object reads the next token from the input until it encounters a space. It’s used to read a single word or a string without spaces.</p>

<ul>
  <li>Printing Output</li>
</ul>

<p>The System.out.println() method is used to print the output to the console, followed by a newline.</p>

<p>This program demonstrates a basic input/output operation in Java. It reads a single string from the user and prints it back, showcasing how to handle simple input and output in a Java program.</p>

<p>This example is a foundational exercise in Java programming, highlighting how to work with basic input and output. Understanding these concepts is crucial as they form the basis for more complex operations and interactions in Java applications. This program can be run in any standard Java environment and is a great starting point for beginners.</p>

<h1 id="print-a-and-b">Print <code class="language-plaintext highlighter-rouge">a</code> and <code class="language-plaintext highlighter-rouge">b</code></h1>

<h3 id="problem-description-1">Problem Description</h3>

<p>You are given two integers, <code class="language-plaintext highlighter-rouge">a</code> and <code class="language-plaintext highlighter-rouge">b</code>. Write a code to take these numbers as input and print them in the format shown in the example.</p>

<h3 id="constraints">Constraints</h3>

<ul>
  <li>100,000 ≤ a, b ≤ 100,000</li>
</ul>

<h3 id="inputoutput-example">Input/Output Example</h3>

<p><strong>Input #1</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>4 5
</code></pre></div></div>

<p><strong>Output #1</strong></p>

<div class="language-css highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">a</span> <span class="o">=</span> <span class="err">4</span>
<span class="nt">b</span> <span class="o">=</span> <span class="err">5</span>

</code></pre></div></div>

<h3 id="solutionjava">Solution.java</h3>

<details>
    <summary>Details</summary>

<pre><code>
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();

        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}
</code></pre>

</details>

<h3 id="explanation-and-concept-overview">Explanation and Concept Overview</h3>

<details>
    <summary>Details</summary>

The task is to read two integers, `a` and `b`, from the user input and print them in a specified format. This is a straightforward problem that tests basic input/output operations in Java.

1. Input
<br />
    - The program uses `Scanner` to read two integers from the user.
<br />
    - `sc.nextInt()` reads the next integer from the input.

2. Output
<br />
    - The program then prints the values of `a` and `b` in the format "a = value" and "b = value".
<br />
    - This is done using `System.out.println()` where the string concatenation operator (`+`) is used to combine the text with the variable values.
<br />
</details>

<h3 id="concept-overview">Concept Overview</h3>

<ul>
  <li>
    <p><strong>Basic Input/Output</strong></p>

    <p>This problem emphasizes understanding how to take input from the user and how to output the data in a specific format. It’s fundamental for beginners to grasp how input and output work in Java.</p>
  </li>
  <li>
    <p><strong>String Concatenation</strong></p>

    <p>The problem also involves string concatenation, where you combine strings and variables to create a desired output format.</p>
  </li>
  <li>
    <p><strong>Using the <code class="language-plaintext highlighter-rouge">Scanner</code> Class:</strong></p>

    <p>The <code class="language-plaintext highlighter-rouge">Scanner</code> class is a part of the <code class="language-plaintext highlighter-rouge">java.util</code> package, and it is widely used for taking input in Java. This problem introduces or reinforces the use of <code class="language-plaintext highlighter-rouge">Scanner</code> to read integers from standard input.</p>
  </li>
</ul>

<p>This problem is a basic exercise in handling input and output in Java, useful for beginners to get accustomed to reading input and printing formatted output.</p>

<h1 id="toggle-case-and-print">Toggle Case and Print</h1>

<h3 id="problem-description-2">Problem Description</h3>

<p>You are given a string <code class="language-plaintext highlighter-rouge">str</code> composed of English alphabets. Write a code to convert each alphabet in the string to its opposite case (uppercase to lowercase, and lowercase to uppercase) and then print the result.</p>

<h3 id="constraints-1">Constraints</h3>

<ul>
  <li>The length of <code class="language-plaintext highlighter-rouge">str</code> is between 1 and 20 inclusive.</li>
  <li><code class="language-plaintext highlighter-rouge">str</code> consists of alphabetic characters only.</li>
</ul>

<h3 id="inputoutput-example-1">Input/Output Example</h3>

<p><strong>Input #1</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>aBcDeFg

</code></pre></div></div>

<p><strong>Output #1</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>AbCdEfG
</code></pre></div></div>

<p>※ The constraints were updated on May 3, 2023.</p>
<h3 id="solution">Solution</h3>

<details>
    <summary>Details</summary>
    <pre><code>
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner sc = new Scanner(System.in);
        
        // Read the input string
        String a = sc.next();
        
        // Create a variable to store the result
        String answer = "";
        
        // Variable to store each character
        char c;
        
        // Loop through each character in the input string
        for(int i = 0; i &lt; a.length(); i++) {
            // Get the character at the current position in the string
            c = a.charAt(i);
            
            // Check if the character is uppercase
            if(Character.isUpperCase(c)) {
                // Convert to lowercase and append to the result
                answer += Character.toLowerCase(c); 
            } else {
                // Convert to uppercase and append to the result
                answer += Character.toUpperCase(c);
            }
        }
        
        // Print the final result
        System.out.println(answer);        
    }
}

</code></pre>

</details>

<h3 id="conceptual-explanation">Conceptual Explanation</h3>
<ol>
  <li><strong>Input Handling</strong>
    <ul>
      <li>The code begins by creating a <code class="language-plaintext highlighter-rouge">Scanner</code> object to read the input string from the user. The <code class="language-plaintext highlighter-rouge">sc.next()</code> function reads the next token of input (in this case, a string) and stores it in the variable <code class="language-plaintext highlighter-rouge">a</code>.</li>
    </ul>
  </li>
  <li><strong>Variable Initialization</strong>
    <ul>
      <li>The variable <code class="language-plaintext highlighter-rouge">answer</code> is initialized as an empty string. This variable will be used to store the final output after converting each character to its opposite case.</li>
      <li>The variable <code class="language-plaintext highlighter-rouge">c</code> is declared to temporarily store each character from the string during the loop.</li>
    </ul>
  </li>
  <li><strong>Looping through the String</strong>
    <ul>
      <li>A <code class="language-plaintext highlighter-rouge">for</code> loop iterates over each character in the string <code class="language-plaintext highlighter-rouge">a</code>. The loop runs from index <code class="language-plaintext highlighter-rouge">0</code> to the length of the string minus one.</li>
    </ul>
  </li>
  <li><strong>Character Case Conversion</strong>
    <ul>
      <li>Inside the loop, the <code class="language-plaintext highlighter-rouge">charAt(i)</code> method is used to get the character at the current index <code class="language-plaintext highlighter-rouge">i</code> of the string.</li>
      <li>The <code class="language-plaintext highlighter-rouge">Character.isUpperCase(c)</code> method checks if the character <code class="language-plaintext highlighter-rouge">c</code> is uppercase.
        <ul>
          <li>If <code class="language-plaintext highlighter-rouge">c</code> is uppercase, it is converted to lowercase using <code class="language-plaintext highlighter-rouge">Character.toLowerCase(c)</code>, and the result is appended to the <code class="language-plaintext highlighter-rouge">answer</code> string.</li>
          <li>If <code class="language-plaintext highlighter-rouge">c</code> is lowercase, it is converted to uppercase using <code class="language-plaintext highlighter-rouge">Character.toUpperCase(c)</code>, and the result is appended to the <code class="language-plaintext highlighter-rouge">answer</code> string.</li>
        </ul>
      </li>
    </ul>
  </li>
</ol>

<blockquote>
  <p>https://docs.oracle.com/javase/8/docs/api/</p>

  <ul>
    <li>
      <p>toLowerCaseConverts the character (Unicode code point) argument to lowercase using case mapping information from the UnicodeData file.</p>

      <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  public static int toLowerCase(int codePoint)
</code></pre></div>      </div>

      <p>Note that <code class="language-plaintext highlighter-rouge">Character.isLowerCase(Character.toLowerCase(codePoint))</code> does not always return <code class="language-plaintext highlighter-rouge">true</code> for some ranges of characters, particularly those that are symbols or ideographs.</p>

      <p>In general, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#toLowerCase--"><code class="language-plaintext highlighter-rouge">String.toLowerCase()</code></a> should be used to map characters to lowercase. <code class="language-plaintext highlighter-rouge">String</code> case mapping methods have several benefits over <code class="language-plaintext highlighter-rouge">Character</code> case mapping methods. <code class="language-plaintext highlighter-rouge">String</code> case mapping methods can perform locale-sensitive mappings, context-sensitive mappings, and 1:M character mappings, whereas the <code class="language-plaintext highlighter-rouge">Character</code> case mapping methods cannot.</p>

      <p><strong>Parameters:</strong><code class="language-plaintext highlighter-rouge">codePoint</code> - the character (Unicode code point) to be converted.<strong>Returns:</strong>the lowercase equivalent of the character (Unicode code point), if any; otherwise, the character itself.<strong>Since:</strong>1.5<strong>See Also:</strong><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isLowerCase-int-"><code class="language-plaintext highlighter-rouge">isLowerCase(int)</code></a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#toLowerCase--"><code class="language-plaintext highlighter-rouge">String.toLowerCase()</code></a></p>
    </li>
  </ul>

  <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public static char toUpperCase(char ch)
</code></pre></div>  </div>

  <p>Converts the character argument to uppercase using case mapping information from the UnicodeData file.</p>

  <p>Note that <code class="language-plaintext highlighter-rouge">Character.isUpperCase(Character.toUpperCase(ch))</code> does not always return <code class="language-plaintext highlighter-rouge">true</code> for some ranges of characters, particularly those that are symbols or ideographs.</p>

  <p>In general, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#toUpperCase--"><code class="language-plaintext highlighter-rouge">String.toUpperCase()</code></a> should be used to map characters to uppercase. <code class="language-plaintext highlighter-rouge">String</code> case mapping methods have several benefits over <code class="language-plaintext highlighter-rouge">Character</code> case mapping methods. <code class="language-plaintext highlighter-rouge">String</code> case mapping methods can perform locale-sensitive mappings, context-sensitive mappings, and 1:M character mappings, whereas the <code class="language-plaintext highlighter-rouge">Character</code> case mapping methods cannot.</p>

  <p><strong>Note:</strong> This method cannot handle <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#supplementary">supplementary characters</a>. To support all Unicode characters, including supplementary characters, use the <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#toUpperCase-int-"><code class="language-plaintext highlighter-rouge">toUpperCase(int)</code></a> method.</p>

  <p><strong>Parameters:</strong><code class="language-plaintext highlighter-rouge">ch</code> - the character to be converted.<strong>Returns:</strong>the uppercase equivalent of the character, if any; otherwise, the character itself.<strong>See Also:</strong><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isUpperCase-char-"><code class="language-plaintext highlighter-rouge">isUpperCase(char)</code></a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#toUpperCase--"><code class="language-plaintext highlighter-rouge">String.toUpperCase()</code></a></p>

</blockquote>

<p><strong>Breif</strong></p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">print</code></strong></li>
</ul>

<p>Outputs data as-is, stays on the same line.</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">println</code></strong></li>
</ul>

<p>Outputs data as-is, then moves to a new line.</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">printf</code></strong></li>
</ul>

<p>Formats and outputs data according to a specified format, stays on the same line unless explicitly told to move to the next line.</p>

<h3 id="summary">Summary</h3>

<p>This code efficiently toggles the case of each character in a string provided by the user. It demonstrates the use of loops, conditionals, and basic string operations in Java. The approach ensures that every character is checked and converted appropriately, resulting in the desired output.</p>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CodingTest" /><category term="CS" /><category term="Java" /><category term="Programming" /><category term="Input/Output" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">[CS] Understanding Asynchronous Transfer Mode (ATM) and Asynchronous Time-Division Multiplexing (ATDM)</title><link href="https://maxkim77.github.io/cs/ATM/" rel="alternate" type="text/html" title="[CS] Understanding Asynchronous Transfer Mode (ATM) and Asynchronous Time-Division Multiplexing (ATDM)" /><published>2024-07-25T00:00:00+00:00</published><updated>2024-07-25T00:00:00+00:00</updated><id>https://maxkim77.github.io/cs/ATM</id><content type="html" xml:base="https://maxkim77.github.io/cs/ATM/"><![CDATA[<p><img src="/assets/images/2024-07-11-CSQuiz1/quiz.png" alt="CSQuiz" /></p>

<h1 id="understanding-asynchronous-transfer-mode-atm-and-asynchronous-time-division-multiplexing-atdm">Understanding Asynchronous Transfer Mode (ATM) and Asynchronous Time-Division Multiplexing (ATDM)</h1>

<h3 id="quiz-question">Quiz Question</h3>

<p><strong>Question:</strong>
Which of the following statements is true regarding Asynchronous Transfer Mode (ATM) and Asynchronous Time-Division Multiplexing (ATDM)?</p>

<p>A. ATM uses variable-length packets for data transmission, while ATDM uses fixed-length cells.</p>

<p>B. ATDM is a specific protocol, whereas ATM is a general multiplexing technique.</p>

<p>C. ATM is connection-oriented and uses fixed-length 53-byte cells, while ATDM dynamically allocates time slots based on demand.</p>

<p>D. In ATM, each type of data is assigned a specific time slot in a repeating cycle, similar to Time-Division Multiplexing (TDM).</p>

<p><strong>Answer:</strong>
C. ATM is connection-oriented and uses fixed-length 53-byte cells, while ATDM dynamically allocates time slots based on demand.</p>

<h3 id="explanation">Explanation</h3>
<ul>
  <li><strong>Option A</strong> is incorrect because ATM uses fixed-length cells (53 bytes), not variable-length packets.</li>
  <li><strong>Option B</strong> is incorrect because ATDM is a general multiplexing technique, while ATM is a specific protocol that uses ATDM principles.</li>
  <li><strong>Option D</strong> is incorrect because ATM does not use fixed time slots in a repeating cycle; it dynamically allocates bandwidth as needed.</li>
  <li><strong>Option C</strong> is correct as it accurately describes the characteristics of both ATM and ATDM.</li>
</ul>

<p>In the world of network technologies, two important concepts often come up: Asynchronous Transfer Mode (ATM) and Asynchronous Time-Division Multiplexing (ATDM). While these terms are closely related, they have distinct characteristics and applications. Let’s dive deeper into these technologies to understand their similarities, differences, and how they work together.</p>

<h2 id="what-is-asynchronous-transfer-mode-atm">What is Asynchronous Transfer Mode (ATM)?</h2>

<p>ATM is a high-speed networking standard designed for transmitting all types of data (such as voice, video, and data traffic) across a network. It is a packet-oriented transmission technology that uses fixed-size cells for data transfer. Each ATM cell is 53 bytes in length, consisting of a 5-byte header and a 48-byte payload.</p>

<h3 id="key-features-of-atm">Key Features of ATM</h3>

<ol>
  <li>
    <p><strong>Fixed-Length Cells</strong>: Unlike other networking protocols that use variable-length packets, ATM uses fixed-length cells of 53 bytes. This standardization simplifies hardware processing and helps maintain consistent transmission delays.</p>
  </li>
  <li>
    <p><strong>Asynchronous Time-Division Multiplexing (ATDM)</strong>: ATM leverages the concept of ATDM, which means that data cells are transmitted asynchronously. Instead of using fixed time slots, each data stream dynamically receives time slots as needed, making efficient use of network resources.</p>
  </li>
  <li>
    <p><strong>Connection-Oriented</strong>: ATM is a connection-oriented protocol. Before data transmission begins, a virtual circuit is established, specifying the path that data will follow through the network. This ensures reliable and consistent data delivery.</p>
  </li>
  <li>
    <p><strong>Quality of Service (QoS)</strong>: ATM supports various levels of Quality of Service (QoS), making it suitable for applications with different performance requirements. It can handle diverse types of traffic, including real-time voice and video, as well as non-real-time data.</p>
  </li>
</ol>

<h2 id="what-is-asynchronous-time-division-multiplexing-atdm">What is Asynchronous Time-Division Multiplexing (ATDM)?</h2>

<p>ATDM is a general multiplexing technique where multiple data streams share the same communication channel by being assigned time slots based on demand. Unlike synchronous time-division multiplexing (TDM), where time slots are fixed, ATDM dynamically allocates time slots to data streams as needed.</p>

<h3 id="key-features-of-atdm">Key Features of ATDM</h3>

<ol>
  <li>
    <p><strong>Dynamic Time Slot Allocation</strong>: ATDM allocates time slots to data streams on an as-needed basis. This means that the channel’s time slots are not fixed and can be used more efficiently by only assigning them when there is data to be transmitted.</p>
  </li>
  <li>
    <p><strong>Efficient Bandwidth Utilization</strong>: By dynamically allocating time slots, ATDM makes better use of the available bandwidth, minimizing idle periods and improving overall transmission efficiency.</p>
  </li>
  <li>
    <p><strong>Flexibility</strong>: ATDM is not tied to a specific protocol and can be implemented in various systems and networks to accommodate different types of traffic and transmission requirements.</p>
  </li>
</ol>

<h2 id="how-atm-and-atdm-work-together">How ATM and ATDM Work Together</h2>

<p>ATM uses ATDM as its underlying multiplexing technique. Here’s how they integrate:</p>

<ul>
  <li><strong>Packet-Oriented Transmission</strong>: ATM’s use of fixed-length 53-byte cells ensures predictable performance and simplifies hardware design.</li>
  <li><strong>Efficient Use of Network Resources</strong>: By employing ATDM, ATM can dynamically allocate time slots for transmitting cells, maximizing the efficiency of the network.</li>
  <li><strong>Connection-Oriented Communication</strong>: ATM sets up a virtual circuit before data transmission, ensuring a reliable and continuous data stream. This connection-oriented nature, combined with ATDM’s efficient time slot allocation, makes ATM suitable for a wide range of applications with varying QoS requirements.</li>
</ul>

<h2 id="diagram-explanation">Diagram Explanation</h2>

<p><img src="/assets/images/2024-07-25-ATM/1.png" alt="Asynchronous Transfer Mode (ATM)" /></p>

<p>This diagram illustrates the concept of ATM and its comparison with TDM. Let’s break down the components and what they represent.</p>

<h3 id="diagram-breakdown">Diagram Breakdown</h3>

<ol>
  <li><strong>Sources of Data</strong>
    <ul>
      <li><strong>Voice</strong>: Represented by gray blocks.</li>
      <li><strong>Data Packets</strong>: Represented by black blocks.</li>
      <li><strong>Images</strong>: Represented by light gray blocks.</li>
    </ul>
  </li>
  <li><strong>Multiplexer (MUX)</strong>
    <ul>
      <li>The MUX is responsible for combining multiple streams of data (voice, data packets, and images) into a single stream for transmission. It acts as a central point where different types of data are synchronized and sent out over the network.</li>
    </ul>
  </li>
  <li><strong>TDM (Time-Division Multiplexing)</strong>
    <ul>
      <li>In TDM, each type of data is assigned a specific time slot in a repeating cycle. For example, voice data might be sent in slot 1, data packets in slot 2, and images in slot 3, and so on.</li>
      <li><strong>Wasted Bandwidth</strong>: TDM can lead to inefficiencies. If a particular time slot has no data to send (e.g., no voice data during a given cycle), that slot is left empty, resulting in wasted bandwidth.</li>
    </ul>
  </li>
  <li><strong>ATM (Asynchronous Transfer Mode)</strong>
    <ul>
      <li>In ATM, data is sent in small, fixed-size cells (53 bytes). Each cell can carry different types of data depending on availability and demand.</li>
      <li>Unlike TDM, ATM does not use fixed time slots. Instead, it dynamically allocates bandwidth as needed. This means there are no empty slots, and bandwidth is used more efficiently.</li>
    </ul>
  </li>
</ol>

<p>In summary, Asynchronous Transfer Mode (ATM) is a sophisticated network technology that combines the principles of Asynchronous Time-Division Multiplexing (ATDM) with fixed-length cells to achieve efficient, reliable, and high-speed data transmission. Understanding the interplay between ATM and ATDM helps in appreciating how modern networks manage diverse types of traffic, ensuring seamless communication and optimal resource utilization. Whether for voice, video, or data, ATM remains a powerful solution for meeting the demands of contemporary networking.</p>]]></content><author><name>Max</name><email>maxkim7723@gmail.com</email></author><category term="CS" /><category term="CS" /><category term="Knowledge" /><category term="Quiz" /><category term="ATM" /><summary type="html"><![CDATA[]]></summary></entry></feed>