Those files, an avalanche of millions of leaked confidential documents from a law firm in Panama, included several pieces of information that incriminated Pakistan’s prime minister at the time, Nawaz Sharif. Evidence began to build that Mr. Sharif had stolen millions of dollars from public coffers in Pakistan to buy expensive apartments in London, under the names of his children.

Mr. Khan capitalized on this and called for Mr. Sharif to resign. The Supreme Court removed Mr. Sharif from office, and just two weeks ago, right before the election, Mr. Sharif and his daughter were imprisoned.

Few would disagree that corruption is out of control in Pakistan. But many observers here saw something in Mr. Sharif’s downfall that was more selective, possibly more sinister.

The widespread suspicion was that Pakistan’s powerful military and intelligence services had pressured the judiciary to take out Mr. Sharif, clearing a path for Mr. Khan to take over. Mr. Sharif had clashed with the army chiefs, even some of those he had chosen, many times. He was a thorn in their side.

Mr. Khan, on the other hand, was someone the military bosses seemed to think they could work with. Analysts said he shared their worldview, in which Pakistan would kowtow less to the United States and talk more with the Taliban and other extremist groups.

In the prelude to the election, the military seemed to push even harder for Mr. Khan. Human rights groups, academics and members of other political parties said security officers threatened politicians to defect to Mr. Khan’s side. Several did.

That does not mean that Mr. Khan was not genuinely popular. He was, especially among young men who lionized him as a sports hero. As elections loomed, a Khan wave swept Pakistan. His face was everywhere — on banners, lampposts and torn flags flying from the sputtering rickshaws that flit in and out of traffic. His supporters were the most energized and confident. His party’s symbol: a cricket bat.