{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreibsnwr4wukhetb34fmmkhnbm7wxage6qmbsh74xv2jqnhxzclfb5m",
"uri": "at://did:plc:25rdn5elo5izoxrmtis34zuk/app.bsky.feed.post/3mp22mmlujif2"
},
"coverImage": {
"$type": "blob",
"ref": {
"$link": "bafkreibuhmn4bjgqsaxb4dwonsvfpckdvbllzv3xkqif4qpssojcj26lx4"
},
"mimeType": "image/webp",
"size": 63696
},
"path": "/jaspreet_singh_86ae1740ac/implement-stack-using-queue-using-single-queue-3g9",
"publishedAt": "2026-06-24T13:15:36.000Z",
"site": "https://dev.to",
"tags": [
"algorithms",
"computerscience",
"java",
"leetcode",
"leetcode.com"
],
"textContent": "\nleetcode.com\n\n\n## Problem Statement\n\nImplement a Stack using only Queue operations.\n\nSupport:\n\n\n\n push()\n pop()\n top()\n empty()\n\n\n## Brute Force Intuition\n\nUse two queues.\n\nPush into first queue.\n\nDuring pop:\n\n\n\n Move n-1 elements\n\n\nto second queue.\n\nRemove last element.\n\nWorks but push becomes easy and pop expensive.\n\n## Moving Towards the Optimal Approach\n\nCan we use:\n\n\n\n Only One Queue ?\n\n\nYes.\n\nWhenever a new element arrives:\n\n\n\n queue.add(x)\n\n\nRotate all older elements behind it.\n\nThis makes newest element appear at front.\n\n## Pattern Recognition\n\n\n Stack\n +\n Queue\n\n => Rotation Trick\n\n\n## Key Observation\n\nAfter inserting:\n\n\n\n 1\n 2\n 3\n\n\nQueue becomes:\n\n\n\n 3 2 1\n\n\nFront always behaves like Stack top.\n\n## Optimal Java Solution\n\n\n class MyStack {\n\n Queue<Integer> mainQ;\n\n public MyStack() {\n\n mainQ = new ArrayDeque<>();\n }\n\n public void push(int x) {\n\n int size = mainQ.size();\n\n mainQ.add(x);\n\n for (int i = 0; i < size; i++) {\n\n int rem = mainQ.remove();\n\n mainQ.add(rem);\n }\n }\n\n public int pop() {\n\n if (!empty())\n return mainQ.poll();\n\n return -1;\n }\n\n public int top() {\n\n if (!empty())\n return mainQ.peek();\n\n return -1;\n }\n\n public boolean empty() {\n return mainQ.isEmpty();\n }\n }\n\n\n## Dry Run\n\n\n push(1)\n\n Queue:\n 1\n\n\n\n push(2)\n\n\nQueue:\n\n\n\n 2 1\n\n\n\n push(3)\n\n\nQueue:\n\n\n\n 3 2 1\n\n\nTop:\n\n\n\n 3\n\n\nPop:\n\n\n\n 3 removed\n\n\n## Complexity Analysis\n\nOperation | Complexity\n---|---\nPush | O(N)\nPop | O(1)\nTop | O(1)\n\n## Interview One-Liner\n\n> Insert element and rotate the queue so the newest element always stays at the front.",
"title": "Implement Stack using Queue (using single queue)"
}