<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Codeforces Archive]]></title><description><![CDATA[Codeforces Archive]]></description><link>https://codeforcesarchive.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 18 Jun 2026 01:22:37 GMT</lastBuildDate><atom:link href="https://codeforcesarchive.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Bitwise Optimisation for Finding the Last Number]]></title><description><![CDATA[🧩 Problem Recap
You’re given a hidden permutation in Equation 1.
$$p = [p_1, p_2, \dots, p_n] \qquad (1)$$You can’t directly access the nth value and can only query using the following instruction, where the inequalities Equations 2 and 3 apply.
$$?...]]></description><link>https://codeforcesarchive.hashnode.dev/bitwise-optimisation-for-finding-the-last-number</link><guid isPermaLink="true">https://codeforcesarchive.hashnode.dev/bitwise-optimisation-for-finding-the-last-number</guid><category><![CDATA[algorithms]]></category><category><![CDATA[bitwise operators]]></category><category><![CDATA[Problem Solving]]></category><category><![CDATA[Competitive programming]]></category><category><![CDATA[Algorithm Design]]></category><dc:creator><![CDATA[Haocheng Lin]]></dc:creator><pubDate>Tue, 04 Nov 2025 13:43:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762263401207/eafe6f98-5e3c-4aa6-8456-3bdf9108ebb4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-recap">🧩 Problem Recap</h2>
<p>You’re given a hidden permutation in Equation 1.</p>
<p>$$p = [p_1, p_2, \dots, p_n] \qquad (1)$$</p><p>You can’t directly access the nth value and can only query using the following instruction, where the inequalities Equations 2 and 3 apply.</p>
<p>$$? \qquad i \qquad x$$</p><p> $$ 1 \leq i \leq n - 1 \qquad (2)$$</p>
<p> $$ 1 \leq x \leq 10^9 \qquad (3)$$</p>
<p>The judge replies:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762262004853/8bcb9df6-7490-4c70-bdea-0e924ea794ed.png" alt class="image--center mx-auto" /></p>
<p>The goal determines the last element at index n in 2n queries. The algorithm uses a bit-by-bit operation expanding from the bitwise partitioning logic on how numbers in a permutation share set bits. Each bit is inferred by comparing the response distributions to the expected value if that bit were 0 or 1.</p>
<h2 id="heading-problem-insight">⚙️ Problem Insight</h2>
<p>Since we can’t query p[n]​ directly, we must <strong>infer its bits indirectly</strong> by observing how other numbers in the permutation interact with various bitmasks. Because the permutation is fixed and non-adaptive, each query gives consistent information about which bits are set in each p[i]. Comparing these results with the full range of numbers, 1…n, determines the missing element.</p>
<h2 id="heading-algorithm">🧠 Algorithm</h2>
<h3 id="heading-step-1-initialise-sets-and-parameters"><strong>Step 1: Initialise sets and parameters</strong></h3>
<ul>
<li><p>Input: an integer n.</p>
</li>
<li><p>Initialise:</p>
<ul>
<li><p><code>rest = {1, 2, …, n-1}</code> : indices that can be queried.</p>
</li>
<li><p><code>likely = {1, 2, …, n}</code> : possible candidates for the nth index value.</p>
</li>
<li><p><code>ans = 0</code> : reconstructed number.</p>
</li>
<li><p><code>D = ⌈log₂(n)⌉</code> : number of bits to test.</p>
</li>
</ul>
</li>
</ul>
<p>This sets up the search space for both indices and candidate values.</p>
<h3 id="heading-step-2-iterate-through-each-bit-position"><strong>Step 2: Iterate through each bit position</strong></h3>
<p>For each bit in the following expression:</p>
<p>$$d=0,1,2,…,D−1$$</p><ol>
<li><strong>Compute the bit mask through Equation 4.</strong></li>
</ol>
<p>$$\text{bit_mask}=1≪d \qquad (4)$$</p><ol>
<li><p><strong>Query all indices in</strong> <code>rest</code>:<br /> For each <strong>i∈rest</strong>:</p>
<ul>
<li><p>Print <code>? i bit_mask</code></p>
</li>
<li><p>Read response <strong>r[i] ∈{0,1}</strong></p>
</li>
<li><p>Partition indices:</p>
<ul>
<li><p><code>index_0</code> ← indices where <strong>r[i]=0</strong></p>
</li>
<li><p><code>index_1</code> ← indices where <strong>r[i]=1</strong></p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Simulate how this bit divides possible numbers:</strong></p>
<ul>
<li><p>Partition <code>likely</code> into:</p>
<ul>
<li><p><code>likely_0</code> ← numbers with this bit = 0</p>
</li>
<li><p><code>likely_1</code> ← numbers with this bit = 1</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Compare counts of responses and theoretical partitions:</strong></p>
<ul>
<li><p>Let: <strong>zeros=∣likely_0∣</strong> , <strong>ones=∣likely_1∣</strong>. If <strong>zeros=∣index_0∣</strong>:</p>
<ul>
<li><p>It means all numbers with <strong>bit = 0</strong> are already used among known indices.</p>
</li>
<li><p>Hence, <strong>p[n]</strong> must have <strong>bit d = 1</strong>.</p>
</li>
<li><p>Set <strong>ans=ans ∣ (1≪d)</strong>.</p>
</li>
<li><p>Update active sets: <strong>rest=index_1</strong>, <strong>likely=likely_1</strong></p>
</li>
</ul>
</li>
<li><p>Else if <strong>ones=∣index_1∣</strong>:</p>
<ul>
<li><p>Then <strong>p[n]</strong> must have <strong>bit d = 0</strong>.</p>
</li>
<li><p>Update: <strong>rest=index_0</strong>, <strong>likely=likely_0</strong></p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Early termination:</strong></p>
<ul>
<li>If <code>likely</code> contains only one element, assign: ans=that element</li>
</ul>
</li>
</ol>
<h3 id="heading-step-3-output-result"><strong>Step 3: Output result</strong></h3>
<p>After processing all bits:</p>
<pre><code class="lang-python">! ans
</code></pre>
<p>This prints the deduced value of p[n]​ to the judge.</p>
<h2 id="heading-complexity">⏱️ Complexity</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762262857145/69fab6e3-df07-44dd-8fc0-135c047d45cc.png" alt class="image--center mx-auto" /></p>
<p>This guarantees the algorithm stays within the problem’s 3-second and 256 MB limits.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762262881434/b6040a1e-8bdd-4035-95e4-13b7632b9378.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-conclusion">✅ Conclusion</h2>
<p>This approach, <strong>bitwise optimisation through logical partitioning</strong>, elegantly transforms a combinatorial search into a deterministic deduction process. By systematically using bit positions as filters, the algorithm determines the unknown element in at most 2n queries. It’s a powerful demonstration of how bit-level reasoning and information theory can solve interactive problems efficiently.</p>
]]></content:encoded></item><item><title><![CDATA[From Stacks to Sparse Tables: Reflections on Two Paths to the Same Problem]]></title><description><![CDATA[One of the most fascinating moments from algorithm design comes from two different implementations attempting to solve the same mathematical challenge. This happened recently while comparing two solutions to a competitive programming problem that req...]]></description><link>https://codeforcesarchive.hashnode.dev/from-stacks-to-sparse-tables-reflections-on-two-paths-to-the-same-problem</link><guid isPermaLink="true">https://codeforcesarchive.hashnode.dev/from-stacks-to-sparse-tables-reflections-on-two-paths-to-the-same-problem</guid><category><![CDATA[Stacks]]></category><category><![CDATA[Dynamic Programming]]></category><category><![CDATA[DSA]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Codeforces]]></category><dc:creator><![CDATA[Haocheng Lin]]></dc:creator><pubDate>Sat, 01 Nov 2025 17:21:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762018122055/634d0430-b91f-4f1d-81aa-015394fb09cf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most fascinating moments from algorithm design comes from two different implementations attempting to solve the same mathematical challenge. This happened recently while comparing two solutions to a competitive programming problem that required summing a specific cost function across all subarrays.</p>
<p>In this post, I’ll reflect on the contrast between a <strong>simplified stack-based heuristic</strong> and a <strong>reference dynamic programming (DP) solution</strong>.</p>
<p>For every contiguous subarray of a sequence, compute a value derived from ratios of its elements, specifically, the ceiling of the last value divided by the minimum value in the subarray, and sum these over all possible partitions.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762017263108/0ee8a20a-91c5-421e-98a3-4a67a55b63bc.png" alt class="image--center mx-auto" /></p>
<p>The first approach used a <strong>monotonous stack</strong> to order elements from left to right, maintaining its structure in segments. This is an example of a greedy algorithm that models the problem like <strong>water flowing downhill</strong>, where each new element reshapes the landscape by merging valleys and accumulates the total cost as a by-product of these merges.</p>
<p>On the other hand, a <strong>dynamic programming and precomputation</strong> method defines and searches all possible cost thresholds, building a multidimensional DP table for each cell and defining the smallest valid left boundary to help partition arrays under a given cost limit.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762017452663/f9d3a290-e302-4a3d-a444-a1176620e98c.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Codeforces 1060 (Div 2) Problem D. Catshock]]></title><description><![CDATA[If you are exploring graph algorithms, the tree structures can look deceptively simple until you encounter recursion depth, node parity, and leaf-handling logic. In this CatShock problem, it combines dynamic leaf update, depth parity, and DFS into on...]]></description><link>https://codeforcesarchive.hashnode.dev/codeforces-1060-div-2-problem-d-catshock</link><guid isPermaLink="true">https://codeforcesarchive.hashnode.dev/codeforces-1060-div-2-problem-d-catshock</guid><category><![CDATA[TreeTraversals]]></category><category><![CDATA[Dynamic Programming]]></category><category><![CDATA[Codeforces]]></category><category><![CDATA[Competitive programming]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Haocheng Lin]]></dc:creator><pubDate>Fri, 24 Oct 2025 09:45:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761298843541/a2550a04-0a34-4cbf-8425-fe9ef3e602f8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are exploring graph algorithms, the tree structures can look deceptively simple until you encounter recursion depth, node parity, and leaf-handling logic. In this CatShock problem, it combines <strong><em>dynamic leaf update</em></strong>, <strong><em>depth parity</em></strong>, and <strong><em>DFS</em></strong> into one elegant algorithm.</p>
<p>I will trace through my final working solution to explain each component.</p>
<h2 id="heading-understanding-the-problem">🧩 Understanding the Problem</h2>
<p>The Catshock problem is a thought-provoking logical puzzle.</p>
<p>You and a cat both live on a tree with <code>n</code> nodes: the cat starts at node <strong>1</strong>, while you reside at node <strong>n</strong>. To help the cat reach you safely, you must write a sequence of instructions in a special “<strong>parkour language</strong>.”</p>
<p>This parkour language supports only two operations:</p>
<ul>
<li><p><code>1</code> The cat moves to any adjacent node.<br />  If there are multiple adjacent nodes, it chooses arbitrarily.<br />  If it has no available moves, it remains in place.</p>
</li>
<li><p><code>2 u</code> The node <code>u</code> and all its connected edges are destroyed.<br />  If the cat happens to be on a node <code>u</code> when it’s destroyed, it dies, so we must avoid that situation.<br />  Destroying an already destroyed node has no effect.</p>
</li>
</ul>
<p>Additionally, there’s an important constraint:</p>
<blockquote>
<p>Two consecutive <code>2 u</code> operations are <strong>not allowed</strong>.</p>
</blockquote>
<p>The challenge lies in constructing a sequence of these instructions such that, <strong>no matter what choices the cat makes</strong>, it will always end up at your node <code>n</code> safely.</p>
<p>Your goal is to guarantee this outcome while keeping the instruction list <strong>no longer than</strong> <code>3n</code> operations, a non-trivial constraint when the cat can make arbitrary moves at every <code>1</code> command.</p>
<p>The heart of the problem is <strong>building a universal sequence of moves and deletions</strong> that forces the cat to end up at your node, regardless of the path it takes.</p>
<p>In other words:</p>
<blockquote>
<p>You must outsmart the cat’s randomness by constructing a resilient traversal–destruction plan on a dynamic tree.</p>
</blockquote>
<p>That’s where the algorithm’s structure, depth-based classification, leaf tracking, and dynamic pruning come into play.</p>
<h2 id="heading-my-plan">🧠 My Plan</h2>
<p>From the start, I knew recursion and graph traversal would play central roles.<br />I broke down the approach as follows:</p>
<ol>
<li><p><strong>Model the tree</strong> using adjacency lists.</p>
</li>
<li><p><strong>Perform a DFS traversal</strong> to record depth, parent, and child counts.</p>
</li>
<li><p><strong>Classify leaves</strong> based on depth parity (even or odd).</p>
</li>
<li><p><strong>Iteratively build operations</strong> that modify leaves while alternating between parity layers.</p>
</li>
</ol>
<p>The solution needed to handle up to hundreds of thousands of recursive calls efficiently, so recursion limits and input speed had to be tuned.</p>
<h2 id="heading-implementation-walkthrough">⚙️ Implementation Walkthrough</h2>
<p>Let’s break down the final version of my code.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sys
sys.setrecursionlimit(<span class="hljs-number">300000</span>)
input = sys.stdin.readline
</code></pre>
<p>Since the problem involves large tree structures, I increased Python’s recursion limit and applied faster input for speed.</p>
<h3 id="heading-step-1-building-the-tree">Step 1: Building the Tree</h3>
<pre><code class="lang-python">n = int(input())
g = [[] <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(n)]
<span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(n - <span class="hljs-number">1</span>):
    u, v = map(int, input().split())
    u -= <span class="hljs-number">1</span>
    v -= <span class="hljs-number">1</span>
    g[u].append(v)
    g[v].append(u)
</code></pre>
<p>Here, <code>g</code> is the adjacency list representation of the tree. Each edge connects two nodes, adjusted for zero-based indexing.</p>
<h3 id="heading-step-2-dfs-to-gather-tree-metadata">Step 2: DFS to Gather Tree Metadata</h3>
<pre><code class="lang-python">dep = [<span class="hljs-number">0</span>] * n  <span class="hljs-comment"># depth of each node</span>
par = [<span class="hljs-number">-1</span>] * n  <span class="hljs-comment"># parent of each node</span>
ch = [<span class="hljs-number">0</span>] * n  <span class="hljs-comment"># number of children</span>
</code></pre>
<p>Now we define our DFS traversal:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dfs</span>(<span class="hljs-params">c, p</span>):</span>
    <span class="hljs-keyword">if</span> p != <span class="hljs-number">-1</span>:
        dep[c] = dep[p] + <span class="hljs-number">1</span>
    par[c] = p
    <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> g[c]:
        <span class="hljs-keyword">if</span> x == p:
            <span class="hljs-keyword">continue</span>
        dfs(x, c)
        ch[c] += <span class="hljs-number">1</span>

dfs(n - <span class="hljs-number">1</span>, <span class="hljs-number">-1</span>)
</code></pre>
<p>We start DFS from the last node (<code>n-1</code>) as the root.<br />Each call updates:</p>
<ul>
<li><p><code>dep[c]</code>: the current node’s depth,</p>
</li>
<li><p><code>par[c]</code>: its parent,</p>
</li>
<li><p><code>ch[c]</code>: the number of direct children.</p>
</li>
</ul>
<h3 id="heading-step-3-leaf-classification-by-depth-parity">Step 3: Leaf Classification by Depth Parity</h3>
<p>Once DFS completes, we classify leaves:</p>
<pre><code class="lang-python">leaves = [[], []]
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(n):
    <span class="hljs-keyword">if</span> ch[i] == <span class="hljs-number">0</span>:
        leaves[dep[i] &amp; <span class="hljs-number">1</span>].append(i)
</code></pre>
<p><code>dep[i] &amp; 1</code> checks the depth parity:</p>
<ul>
<li><p>0 → even depth</p>
</li>
<li><p>1 → odd depth</p>
</li>
</ul>
<p>We store leaf nodes into <code>leaves[0]</code> or <code>leaves[1]</code> accordingly.</p>
<h3 id="heading-step-4-generating-the-operation-sequence">Step 4: Generating the Operation Sequence</h3>
<p>Now comes the fun part — alternating operations between parity groups.</p>
<pre><code class="lang-python">ans = []
col = dep[<span class="hljs-number">0</span>] &amp; <span class="hljs-number">1</span>

<span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(n - <span class="hljs-number">1</span>):
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> leaves[col ^ <span class="hljs-number">1</span>]:
        ans.append((<span class="hljs-number">1</span>, <span class="hljs-number">-1</span>))
        col ^= <span class="hljs-number">1</span>
    nxt = leaves[col ^ <span class="hljs-number">1</span>].pop()
    ans.append((<span class="hljs-number">2</span>, nxt))

    p = par[nxt]
    ch[p] -= <span class="hljs-number">1</span>
    <span class="hljs-keyword">if</span> ch[p] == <span class="hljs-number">0</span>:
        leaves[dep[p] &amp; <span class="hljs-number">1</span>].append(p)
    ans.append((<span class="hljs-number">1</span>, <span class="hljs-number">-1</span>))
    col ^= <span class="hljs-number">1</span>
</code></pre>
<p>Let’s break this down:</p>
<ul>
<li><p><code>col</code> tracks the current depth parity we’re working with.</p>
</li>
<li><p>If the opposite parity list is empty, we insert a <strong>type 1 operation</strong> (a placeholder or parity switch).</p>
</li>
<li><p>Otherwise, we pick a leaf (<code>nxt</code>) from the opposite group and perform a <strong>type 2 operation</strong> on it.</p>
</li>
<li><p>We then reduce its parent’s child count.<br />  If the parent becomes a leaf, we add it to the corresponding parity list.</p>
</li>
</ul>
<p>This alternating mechanism ensures both parities are processed fairly, and the structure dynamically updates as the tree “collapses” upwards.</p>
<h3 id="heading-step-5-formatting-the-output">Step 5: Formatting the Output</h3>
<pre><code class="lang-python">out = [str(len(ans))]
<span class="hljs-keyword">for</span> x, y <span class="hljs-keyword">in</span> ans:
    <span class="hljs-keyword">if</span> x == <span class="hljs-number">1</span>:
        out.append(<span class="hljs-string">"1"</span>)
    <span class="hljs-keyword">else</span>:
        out.append(<span class="hljs-string">f"2 <span class="hljs-subst">{y + <span class="hljs-number">1</span>}</span>"</span>)
<span class="hljs-keyword">return</span> <span class="hljs-string">'\n'</span>.join(out)
</code></pre>
<p>Each operation is printed in the required format:</p>
<ul>
<li><p><code>1</code> for a basic operation</p>
</li>
<li><p><code>2 X</code> for an operation involving a node <code>X</code></p>
</li>
</ul>
<p>The program supports multiple test cases using:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    t = int(input())
    results = []
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(t):
        results.append(solve())
    print(<span class="hljs-string">'\n\n'</span>.join(results))
</code></pre>
<h2 id="heading-final-thoughts">🚀 Final Thoughts</h2>
<p>The key to cracking <strong>CatShock</strong> wasn’t in finding a fancy algorithm, but in a dynamic, recursive, structured algorithm that maintains parity balance.</p>
<p>Some lessons from this experience:</p>
<ul>
<li><p>DFS metadata (like <em>parent</em> and <em>depth</em>) can drastically simplify post-processing logic.</p>
</li>
<li><p>Maintaining dynamic leaf sets is cleaner than recalculating after each operation.</p>
</li>
<li><p>Even simple parity tricks can guide complex operation flows.</p>
</li>
</ul>
<p>This challenge reminded me that elegant graph solutions often lie in <strong>how you manage your recursion and state transitions</strong>, not in the number of lines of code you write.</p>
<h2 id="heading-takeaway">🧩 Takeaway</h2>
<p>If you’re dealing with recursive tree problems:</p>
<ul>
<li><p>Track parents, depths, and children separately.</p>
</li>
<li><p>Think in layers (even/odd or levels).</p>
</li>
<li><p>Use stacks or lists for tracking leaves dynamically instead of recalculating.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Reverse XOR: Cracking the Palindrome Code (Codeforces Problem)]]></title><description><![CDATA[When I first read the Reverse XOR problem on Codeforces, my instinct was to reach for a brute-force loop. After all, the task seems simple:
Does there exist a positive integer x such that x ⊕ reverse(x) = n?
Where reverse(x) means reversing the binar...]]></description><link>https://codeforcesarchive.hashnode.dev/reverse-xor-cracking-the-palindrome-code-codeforces-problem</link><guid isPermaLink="true">https://codeforcesarchive.hashnode.dev/reverse-xor-cracking-the-palindrome-code-codeforces-problem</guid><category><![CDATA[Codeforces]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[data structures]]></category><category><![CDATA[binary]]></category><category><![CDATA[code optimization]]></category><dc:creator><![CDATA[Haocheng Lin]]></dc:creator><pubDate>Wed, 15 Oct 2025 11:39:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1760528043862/06057c39-2536-4fb4-93a2-20e3de9e0c44.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When I first read the Reverse XOR problem on Codeforces, my instinct was to reach for a brute-force loop. After all, the task seems simple:</p>
<p><em>Does there exist a positive integer</em> <code>x</code> <em>such that</em> <code>x ⊕ reverse(x) = n</code><em>?</em></p>
<p>Where <code>reverse(x)</code> means reversing the binary representation of <code>x</code>.<br />For example:</p>
<ul>
<li><p><code>x = 12 (1100₂)</code> → <code>reverse(x) = 3 (0011₂)</code></p>
</li>
<li><p><code>2 ⊕ 1 = 3</code></p>
</li>
</ul>
<p>Brute force methods often struggle when dealing with large inputs that contain up to 10,000 or even millions of values. In these cases, the potential value can be as high as 2³⁰, making it impractical to check through all possible values iteratively.</p>
<p>In this post, I will walk through an optimal solution, explaining why it works and how it can be applied in real-world problem-solving scenarios.</p>
<p>🧠 <strong>Step 1</strong>: The Naïve Brute Force</p>
<p>With the starter code functions</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">reverse_binary</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">return</span> int(bin(n)[<span class="hljs-number">2</span>:][::<span class="hljs-number">-1</span>], <span class="hljs-number">2</span>)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">solve</span>(<span class="hljs-params">n</span>):</span>
    max_x = min(n + <span class="hljs-number">1000</span>, <span class="hljs-number">2</span>**<span class="hljs-number">20</span>)
    <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, max_x + <span class="hljs-number">1</span>):
        <span class="hljs-keyword">if</span> x ^ reverse_binary(x) == n:
            <span class="hljs-keyword">return</span> <span class="hljs-string">"YES"</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">"NO"</span>
</code></pre>
<p>These current functions can process small numbers, but cause TLE issues on bigger test sets. This reveals a hidden structure within the XOR operation combined with reversal.</p>
<p>🪄 <strong>Step 2</strong>: Looking at Patterns</p>
<p>I debugged and displayed <code>x ⊕ reverse(x)</code> for different <code>x</code> values and looked for patterns in the binary strings.</p>
<p><code>x⊕reverse(x)=n</code></p>
<p>Suppose that the binary <code>x</code> has a length of <code>k</code>. Reversing the number mirrors the centre bits, implying that the number’s bit structure must mirror itself.</p>
<pre><code class="lang-python">x       =  <span class="hljs-number">10010</span>
reverse =  <span class="hljs-number">01001</span>
xor     =  <span class="hljs-number">11011</span>   ← palindrome
</code></pre>
<p>A rare case is when <code>k</code> is an odd number, when the middle bit is calculated by <code>b_mid ⊕ b_mid = 0</code>.</p>
<p>🧩 <strong>Step 3</strong>: Trailing Zeros</p>
<p>Leading zeros in reversed binary carry no significance and can be removed.</p>
<p>🧪 <strong>Step 4</strong>: The Final Efficient Solution</p>
<p>The following code block contains the final complete implementation.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sys

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_valid</span>(<span class="hljs-params">n: int</span>) -&gt; bool:</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    s = bin(n)[<span class="hljs-number">2</span>:]
    a = s.rstrip(<span class="hljs-string">'0'</span>)
    <span class="hljs-keyword">if</span> a != a[::<span class="hljs-number">-1</span>]:  <span class="hljs-comment"># must be a palindrome</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    <span class="hljs-keyword">if</span> len(a) % <span class="hljs-number">2</span> == <span class="hljs-number">1</span> <span class="hljs-keyword">and</span> a[len(a)//<span class="hljs-number">2</span>] == <span class="hljs-string">'1'</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    input = sys.stdin.readline
    t = int(input())
    out = []
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(t):
        n = int(input())
        out.append(<span class="hljs-string">"YES"</span> <span class="hljs-keyword">if</span> is_valid(n) <span class="hljs-keyword">else</span> <span class="hljs-string">"NO"</span>)
    print(<span class="hljs-string">"\n"</span>.join(out))

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    main()
</code></pre>
<p>This is an efficient solution with an <code>O(t)</code> time complexity, enabling the application to process big data.</p>
]]></content:encoded></item></channel></rss>